【问题标题】:How to use the "with" statement inside an eex template in elixir phoenix如何在 elixir phoenix 的 eex 模板中使用“with”语句
【发布时间】:2021-10-07 18:49:18
【问题描述】:

我想运行以下代码:

<%= 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.

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

<%= 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

【问题讨论】:

    标签: elixir phoenix-framework


    【解决方案1】:

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

    也就是说,要么您需要使用 else 处理这两种可能的情况,要么确保返回的内容是可渲染的(就像您的 :foo &lt;- :bar 一样)

    会发生什么,&lt;%= 尝试渲染不匹配的 day_data 并失败。


    要介绍else,应该使用以下语法

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

    【讨论】:

    • 哦,我明白了。仍然.. 不知何故,我没有克服 else 子句的语法错误。我尝试了&lt;% else %&gt; &lt;%= _err -&gt; nil %&gt; 的各种组合。它不喜欢-&gt;。我尝试的第二个建议(见问题)。即使匹配成功也不打印任何内容。
    • 我已经用else更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多