Initial commit: there's still tons of base Phoenix boilerplate to remove, but the...
[tech-radar-editor.git] / web / views / error_helpers.ex
1 defmodule TechRadarEditor.ErrorHelpers do
2 @moduledoc """
3 Conveniences for translating and building error messages.
4 """
5
6 use Phoenix.HTML
7
8 @doc """
9 Generates tag for inlined form input errors.
10 """
11 def error_tag(form, field) do
12 if error = form.errors[field] do
13 content_tag :span, translate_error(error), class: "help-block"
14 end
15 end
16
17 @doc """
18 Translates an error message using gettext.
19 """
20 def translate_error({msg, opts}) do
21 # Because error messages were defined within Ecto, we must
22 # call the Gettext module passing our Gettext backend. We
23 # also use the "errors" domain as translations are placed
24 # in the errors.po file.
25 # Ecto will pass the :count keyword if the error message is
26 # meant to be pluralized.
27 # On your own code and templates, depending on whether you
28 # need the message to be pluralized or not, this could be
29 # written simply as:
30 #
31 # dngettext "errors", "1 file", "%{count} files", count
32 # dgettext "errors", "is invalid"
33 #
34 if count = opts[:count] do
35 Gettext.dngettext(TechRadarEditor.Gettext, "errors", msg, msg, count, opts)
36 else
37 Gettext.dgettext(TechRadarEditor.Gettext, "errors", msg, opts)
38 end
39 end
40 end