Rbtz. CredoChecks. Refactor. PreferForAttrOverForBlock
(rbtz_credo_checks v0.3.0)
Copy Markdown
View Source
Basics
This check is disabled by default.
Learn how to enable it via .credo.exs.
This check has a base priority of normal and works with any version of Elixir.
Explanation
Prefers the :for={item <- @collection} attribute directly on an element
over a <%= for ... do %> EEx block when the block wraps a single
element.
When the loop body is just one element, <el :for={...}> reads cleaner
and keeps the iteration attached to the element being repeated. Reserve
<%= for %> for loops that genuinely need to emit two or more sibling
elements per iteration.
The check inspects every ~H sigil and every .heex template referenced
via embed_templates. It locates each <%= for ... do %> block, scans
its body for top-level HTML/HEEx elements (skipping nested EEx blocks),
and flags the block when exactly one element is found.
Bad
<%= for item <- @items do %>
<li>{item.name}</li>
<% end %>Good
<li :for={item <- @items}>{item.name}</li>
<%= for item <- @items do %>
<dt>{item.name}</dt>
<dd>{item.value}</dd>
<% end %>Check-Specific Parameters
There are no specific parameters for this check.
General Parameters
Like with all checks, general params can be applied.
Parameters can be configured via the .credo.exs config file.