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

How to use the "with" statement inside an eex template in elixir phoenix

我想要运行以下代码:

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

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

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

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


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

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