Phoenix.HTML.Safe for custom structs

My app has schemas with translatable fields.

defmodule Translation do
  embedded_schema do
     field :en, :string
     field :fr, :string
     field :de, :string
   end

   def translate(translation) do
     locale = Gettext.get_locale(MyApp.Gettext)
     #...
   end
end

defmodule Project do
  schema "projects" do
     embeds_one :title, Translation 
   end
end

Now, instead of writing everywhere

<%= Translation.translate(project.title) %>

I used protocol:

defimpl Phoenix.HTML.Safe, for: Translation do
  def to_iodata(translation) do
     Phoenix.HTML.Safe.to_iodata(Translation.translate(translation))
  end
end

which automagically translates texts in templates.

<%= project.title %>

This works so well that I got suspicious. Do you see disadvantages of this approach? Or better solution?

3 Likes

That seems like a great use of the protocol to me. :slight_smile:

Make sure the translatation is truly safe though.

1 Like

I don’t have to, thanks to call to Phoenix.HTML.Safe.to_iodata on translated text.

1 Like

Ah you are implementing Phoenix.HTML.Safe! You are right, that one you have to ‘safe’ it yourself, so that is good, ignore me. ^.^