error_helpers.ex 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. defmodule WebWeb.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. # Because error messages were defined within Ecto, we must
  19. # call the Gettext module passing our Gettext backend. We
  20. # also use the "errors" domain as translations are placed
  21. # in the errors.po file.
  22. # Ecto will pass the :count keyword if the error message is
  23. # meant to be pluralized.
  24. # On your own code and templates, depending on whether you
  25. # need the message to be pluralized or not, this could be
  26. # written simply as:
  27. #
  28. # dngettext "errors", "1 file", "%{count} files", count
  29. # dgettext "errors", "is invalid"
  30. #
  31. if count = opts[:count] do
  32. Gettext.dngettext(WebWeb.Gettext, "errors", msg, msg, count, opts)
  33. else
  34. Gettext.dgettext(WebWeb.Gettext, "errors", msg, opts)
  35. end
  36. end
  37. end