使用 Phoenix EEX 模板时如何在 Gettext 字符串中嵌入 Link?
How Do You Embed a Link in a Gettext String When Using Phoenix EEX Templates?
当使用 I18n.t
在 Rails 中嵌入 link 时,可以在 ERB 中做这样的事情:
<% link_destination = link_to(I18n.t(".link destination", "https://destination.url")) %>
<%= I18n.t(".translated text with %{link}", link: link_destination) %>
但是当我在 Phoenix / Elixir EEX 中做这样的事情时:
<% link_destination = link(gettext("link destination"), to: "https://destination.url")
<%= raw(gettext("translated text with %{link}", link: link_destination)) %>
我收到错误:
(Protocol.UndefinedError) protocol String.Chars not implemented for
{:safe, [60, "a", [[32, "href", 61, 34, "https://destination.url",
34]], 62, "link destination", 60, 47, "a", 62]} of type Tuple.
那么如何在 Gettext 翻译中嵌入 URL?
错误表明我们需要将Phoenix.HTML.link/2
函数的输出转换为字符串。为此,我们可以添加对 Phoenix.HTML.safe_to_string/1
的中间调用,以将输出转换为将要嵌入的字符串。
所以前面的例子最终看起来像这样:
<% link_destination = safe_to_string(link(gettext("link destination"), to: "https://destination.url"))
<%= raw(gettext("translated text with %{link}", link: link_destination)) %>
当使用 I18n.t
在 Rails 中嵌入 link 时,可以在 ERB 中做这样的事情:
<% link_destination = link_to(I18n.t(".link destination", "https://destination.url")) %>
<%= I18n.t(".translated text with %{link}", link: link_destination) %>
但是当我在 Phoenix / Elixir EEX 中做这样的事情时:
<% link_destination = link(gettext("link destination"), to: "https://destination.url")
<%= raw(gettext("translated text with %{link}", link: link_destination)) %>
我收到错误:
(Protocol.UndefinedError) protocol String.Chars not implemented for {:safe, [60, "a", [[32, "href", 61, 34, "https://destination.url", 34]], 62, "link destination", 60, 47, "a", 62]} of type Tuple.
那么如何在 Gettext 翻译中嵌入 URL?
错误表明我们需要将Phoenix.HTML.link/2
函数的输出转换为字符串。为此,我们可以添加对 Phoenix.HTML.safe_to_string/1
的中间调用,以将输出转换为将要嵌入的字符串。
所以前面的例子最终看起来像这样:
<% link_destination = safe_to_string(link(gettext("link destination"), to: "https://destination.url"))
<%= raw(gettext("translated text with %{link}", link: link_destination)) %>