elixir - 如何在 elixir phoenix 的 eex 模板中使用 "with"语句

标签 elixir phoenix-framework

我想运行以下代码:

<%= with [%{time: time}| _rest] <- day_data do %>
  <p><%= Timex.lformat!(time, "{WDshort}", Gettext.get_locale()) %></p>
<% end %>

但这引发了 (Protocol.UndefinedError) protocol Phoenix.HTML.Safe not implemented for %{} of type Map。

然后我尝试了一些 super 简单的方法:

<%= with :foo <- :bar do %>
  <p><%= "eex shouldn't print this" %></p>
<% end %>

这让我在模板中呈现“bar”。什么?这?实际的?酒吧?

我也试过不带等号,但没有包含模板中的代码。

<% with number <- 1 do %>
  <p><%= "eex does not print this #{number}" %></p>
<% end %>

我什至可以在 eex 模板中使用 with 语句吗?或者我必须去:

<%= if match?([%{time: time}| _rest], day_data) do %>
  <% [%{time: time}| _rest] = day_data %>
  <p><%= Timex.lformat!(time, "{WDshort}", Gettext.get_locale()) %></p>
<% end %>

顺便说一句,我不敢相信以前没有人问过这个问题。我试图寻找答案。抱歉,如果结果是重复的。

在第一个答案后编辑: 我也试过(之前的语法错误:'->'):

<%= with [%{time: time}| _rest] <- day_data do %>
  <p><%= Timex.lformat!(time, "{WDshort}", Gettext.get_locale()) %></p>
<% else %>
  <%= _err -> nil %>
<% end %>

没有子句(“with”中的 :else 需要 -> 子句)

<%= with [%{time: time}| _rest] <- day_data do %>
  <p><%= Timex.lformat!(time, "{WDshort}", Gettext.get_locale()) %></p>
<% else %>
<% end %>

以及使用或不使用等号的各种可能方式。还用空字符串交换了 nil 以确保安全。

最佳答案

Kernel.SpecialForms.with/1 如果没有匹配,立即返回 RHO。

也就是说,要么你需要用 else 处理这两种可能的情况或确保返回的内容是可渲染的(如您的 :foo <- :bar 的情况。)

发生了什么,是<%=尝试呈现不匹配 day_data并失败了。


介绍else应该使用以下语法

<%= with foo <- 42 do %>
  <p><%= MATCH: #{foo} %></p>
<% else _ -> %>
  <p><%= NO MATCH %></p>
<% end %>

关于elixir - 如何在 elixir phoenix 的 eex 模板中使用 "with"语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69478640/

相关文章:

elixir - phoenix elixir exaws 与 minio 配合使用(上传文件)

spring-boot - 了解 Elixir

elixir - 在 Phoenix 中使用重定向时如何发送参数

dictionary - Elixir 按条件过滤映射条目

erlang - 如何运行由 Elixir 或 Erlang 编译的梁文件?

templates - Phoenix : render template of other folder

elixir - 在 Phoenix 中使用 Ecto 获取数据时仅获取特定字段

elixir - Phoenix Code_Reloader 是否只重新加载 Elixir 代码?

elixir - Phoenix 实时重新加载因编译错误而中断

csv - Elixir:尝试将映射写入 CSV,被写入为流结果