Dynamic add a class to tr - Solution found!

Hi,
I am new to Phoenix.
Here is I am trying to achieve.
I have a list and I want to iterate over it and if the row is even add a css class otherwise add another one
For some reason I get

index.html.heex:40:19: expected closing `>` or `/>`

My code

<%= for {user, idx} <- Enum.with_index(@users) do %>
              <tr <%= if rem(idx, 2) == 0 do %> class="bg-white" <% else %> class="bg-gray-50" <% end %>  >
           

If I put that if in a td it works file.
I have search quite a bit but I can not figure it out.
Thanks for the help.

1 Like

Hello and welcome,

You should use something like this with the new heex syntax…

<tr class={if ..., do: ..., else: ...}>
...
</tr>

Your syntax is not valid.

4 Likes

Thank you so much!
I really appreciate it!

1 Like

This is the new syntax for html attributes, otherwise You would use <%= %>, as usual.

As a side note, what You try could be done by adding class table-striped to a table element in Bootstrap.

I am quite surprised there is no real equivalent in Tailwind.

This can also be done in CSS.

tr:nth-child(even) {
  background-color: #f2f2f2;
}
2 Likes

Hi,
Forgot about the css trick.
I just started learning Phoenix after 18 years of web development with Python/Php/Ruby/Node. Wanted to try something new.
I like it so far but the template system can be improved I think.

Just another approach:

<body class={"fixed-left #{if @current_user do 'login-page' end}"}>

1 Like

Where are the docs for this? If this is still valid?

It’s the syntax for heex and is valid since it’s introduction.

You might find some info here…

You have new syntax in the latest live_view… like

:if={}
:for={}