Faulty nesting in .heex

Viewed 107

While converting old .eex into .heex I stumbled upon this code which uses TailwindCSS to display zebra style table rows:

<%= for {language, counter} <- Enum.with_index(@languages) do %>
  <tr class="<%= if rem(counter, 2) == 0, do: "bg-white", else: "bg-gray-50" %>">

It results into this error while running mix format

$ mix format
mix format failed for file: lib/w_games_web/templates/language/index.html.heex
** (Phoenix.LiveView.HTMLTokenizer.ParseError) nofile:2:14: expected closing `"` for attribute value

I kind of understand the problem and then I don't.

  • How can I fix this?
  • Is there a better/cleaner way to achieve the wanted zebra code effect?
1 Answers

With HEEx, HTML attributes have to be generated this way:

<tr class={if rem(counter, 2) == 0, do: "bg-white", else: "bg-gray-50"}>

In short, attr="<%= value %>" (EEx) becomes attr={value} (HEEx).

Note: you can use CSS(3) to alternate colors (:nth-child(odd/even)) and use the Integer.is_odd/even/1 guards in Elixir

Related