Skip to content

Instantly share code, notes, and snippets.

@noelworden
Last active June 29, 2020 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noelworden/a754e438b0b719105cffbc5b66a89fb1 to your computer and use it in GitHub Desktop.
Save noelworden/a754e438b0b719105cffbc5b66a89fb1 to your computer and use it in GitHub Desktop.
defmodule FinanceWeb.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
use Phoenix.HTML
@doc """
Generates tag for inlined form input errors.
"""
def error_tag(form, field) do
Enum.map(Keyword.get_values(form.errors, field), fn error ->
content_tag(:span, translate_error(error), class: "help-block")
end)
end
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# When using gettext, we typically pass the strings we want
# to translate as a static argument:
#
# # Translate "is invalid" in the "errors" domain
# dgettext("errors", "is invalid")
#
# # Translate the number of files with plural rules
# dngettext("errors", "1 file", "%{count} files", count)
#
# Because the error messages we show in our forms and APIs
# are defined inside Ecto, we need to translate them dynamically.
# This requires us to call the Gettext module passing our gettext
# backend as first argument.
#
# Note we use the "errors" domain, which means translations
# should be written to the errors.po file. The :count option is
# set by Ecto and indicates we should also apply plural rules.
if count = opts[:count] do
Gettext.dngettext(FinanceWeb.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(FinanceWeb.Gettext, "errors", msg, opts)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment