error_helpers.ex 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. defmodule GiomWeb.ErrorHelpers do
  2. @moduledoc """
  3. Conveniences for translating and building error messages.
  4. """
  5. use Phoenix.HTML
  6. @doc """
  7. Generates tag for inlined form input errors.
  8. """
  9. def error_tag(form, field) do
  10. Enum.map(Keyword.get_values(form.errors, field), fn (error) ->
  11. content_tag :span, translate_error(error), class: "help-block"
  12. end)
  13. end
  14. @doc """
  15. Translates an error message using gettext.
  16. """
  17. def translate_error({msg, opts}) do
  18. # When using gettext, we typically pass the strings we want
  19. # to translate as a static argument:
  20. #
  21. # # Translate "is invalid" in the "errors" domain
  22. # dgettext "errors", "is invalid"
  23. #
  24. # # Translate the number of files with plural rules
  25. # dngettext "errors", "1 file", "%{count} files", count
  26. #
  27. # Because the error messages we show in our forms and APIs
  28. # are defined inside Ecto, we need to translate them dynamically.
  29. # This requires us to call the Gettext module passing our gettext
  30. # backend as first argument.
  31. #
  32. # Note we use the "errors" domain, which means translations
  33. # should be written to the errors.po file. The :count option is
  34. # set by Ecto and indicates we should also apply plural rules.
  35. if count = opts[:count] do
  36. Gettext.dngettext(GiomWeb.Gettext, "errors", msg, msg, count, opts)
  37. else
  38. Gettext.dgettext(GiomWeb.Gettext, "errors", msg, opts)
  39. end
  40. end
  41. end