Background
I am using Phoenix’s templating language with ~H
and I want to mark some checkboxes as checked depending on some condition.
To achieve this, I have this code:
defp syndicate_checkbox(assigns) do
assigns = Enum.into(assigns, %{})
if Map.get(assigns, :checked) do
~H"""
<div class="row single-syndicate">
<input class="column single-checkbox" type="checkbox" id={@synd.id}
name="syndicates[]" value={@synd.id} checked>
<label for={@synd.id} class="column"><%= @synd.name %></label>
</div>
"""
else
~H"""
<div class="row single-syndicate">
<input class="column single-checkbox" type="checkbox" id={@synd.id}
name="syndicates[]" value={@synd.id}>
<label for={@synd.id} class="column"><%= @synd.name %></label>
</div>
"""
end
end
Now, this function works but all the duplication leaves a terrible taste in my mouth.
Specifically because the only difference here is this 1 line:
<input class="column single-checkbox" type="checkbox" id={@synd.id}
name="syndicates[]" value={@synd.id} checked>
Namelly, the checked
word.
Problem
Normally I would do something like:
<input class="column single-checkbox" type="checkbox" id={@synd.id}
name="syndicates[]" value={@synd.id} {mark_checked(true)}>
and somewhere in the same file:
defp mark_checked(true), do: "checked"
defp mark_checked(_), do: ""
However the issue with this is that "checked"
or ""
are strings, which means the code inside ~H
will not compile.
Question
How do I remove this duplication?