Snytax troubles: Heex string interpolation in html element's attributes

Hi! I’m working in a liveview and want to fill attributes such as id, for label and title with a value from a for-loop.

<ul>
      <%= for item <- ["apple", "bread", "peanut butter"] do %>
        <li>
          <input type="checkbox" checked="checked" id="<%= item %>" />
          <label class="tree_label" for="<%= item %>"> <%= item %>  </label>
        </li>
      <% end %>
</ul>

but I get this error:
Make sure the attribute is properly closed. This may also happen if
there is an EEx interpolation inside a tag, which is not supported.
Instead of

<div <%= @some_attributes %>>
</div>

do

<div {@some_attributes}>
</div>

but my values are from a loop rather than the socket so the @ doesn’t work nor does adding { } around the item like so:
<input type="checkbox" checked="checked" id="{item}" />
or <input type="checkbox" checked="checked" id="#{item}" />

The {} and the @ are different parts of the picture.

Element attributes in heex are supplied either as attr="…" for static values or as attr={…} for dynamic values. For the latter can be any elixir code returning a string (or convertable to string data) or a boolean.

There’s also <tag {…}> where can be a keyword list or map of attributes → values.

@var is a macro to access assigns off of the socket. It can be used in either of the places before where elixir code is allowed, but doesn’t need to be used.

2 Likes