kminevskiy
Conditional rendering in LiveView template
Hey folks,
Does anyone know what could cause the following behavior: I have a live view template and in it I conditionally render a form (based on the value inside the socket assigns).
<%= if length(@users) > 0 do %>
...
<% end %>
When the length changes, it used to render a form, but now nothing happens. If I prepend that first line with, say, a tag <p><%= length(@users) %></p> Everything (showing the form dynamically based on the length of @users list) works as expected. I am pretty sure the code worked as is a few weeks ago before I updated to the latest Live View (but I’m not even sure it’s an issue with Live View), among other packages. Am I missing some new behavior introduced recently or is there something else I’m not doing correctly?
Most Liked Responses
NobbZ
You shouldn’t to length like this. This will always iterate and count the full list.
Use something like match?([_|_], @users) instead.
PJUllrich
This might not help in this particular case, but I recently learned that a template gets rendered and send over the websocket connection every time the socket assigns are changed when it isn’t in the .leex format, so when it is a .eex file. Just changing all file formats to .leex reduced the websocket traffic by a lot! So, whenever you do <%= render "my_template.html", assigns %> inside a template, make sure that my_template is of the format .leex ![]()
carterbryden
I had a similar issue with conditional rendering with liveview. I posted an issue but I just haven’t had enough time to create a reproduction repo publically (client project). In my case it seemed like it might be related to a nested liveview inside a conditional in a liveview template. Still don’t have a fix for it, I just changed the way I was rendering things to work around needing the if statement. I’ll post here if I do figure it out.








