When using I18n.t
to embed a link in Rails, one could do something like this in an ERB:
<% link_destination = link_to(I18n.t(".link destination", "https://destination.url")) %>
<%= I18n.t(".translated text with %{link}", link: link_destination) %>
But when I do something like this in a Phoenix / Elixir EEX:
<% link_destination = link(gettext("link destination"), to: "https://destination.url")
<%= raw(gettext("translated text with %{link}", link: link_destination)) %>
I get the error:
(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.
So how do I embed a URL in a Gettext translation?
The error indicates that we need to convert the output of the Phoenix.HTML.link/2
function to a string. To do this, we can add an intermediary call to Phoenix.HTML.safe_to_string/1
to convert the output to a string that will be embedded.
So the previous example ends up looking something like this:
<% link_destination = safe_to_string(link(gettext("link destination"), to: "https://destination.url"))
<%= raw(gettext("translated text with %{link}", link: link_destination)) %>