coming other programming languages, many me in surprise. have simple problem. have list - say, users. want iterate through users , display information. pretty simple until got stumped this:
using eex template, trying this:
<%= <- 0..length(@users) %> <% user = enum.at(@users) %> <!-- every third user, need display on new "row" --> <%= if rem(i,3) == 0 %> <div class="row"> <% end %> <!-- display user information - user name --> <%= user.name %> <!-- close out "row" tag if due starting on next iteration --> <%= if rem(i+1,3) == 0 %> <div class="row"> <% end %> <% end %> firstly, user value turning out nil. not sure why. secondly, don't have explanation this.
what difference between "user = enum.at(@users, i)" , <%= user <- @users %>? in latter case, user not nil.
finally, best way keep track of times through list , take different action (like starting user on new row in example above)?
to keep things simple, have ignored fact may not have final closing "/div" tag row (which depends on number of users in list). i've ignored putting logic around focus on issue @ hand.
what difference between
user = enum.at(@users, i),<%= user <- @users %>? in latter case, user not nil.
you should getting user = nil last iteration. that's because you're looping 0 length(@users), , last iteration value length(@users) 1 more last valid index in list indexing 0 based. should loop 0 length(@users) - 1. note cause problems if @users empty enum.to_list(0..-1) #=> [0, -1].
finally, best way keep track of times through list , take different action (like starting user on new row in example above)?
i use enum.with_index , if. also, length in elixir slow (o(n)) operation, it's best cache value outside loop instead of recalculating on every iteration. believe meant print "</div>" in second if. here's final code:
<% users_length = length(@users) %> <%= {user, i} <- enum.with_index(@users) %> <%= if rem(i, 3) == 0, do: ~s|<div class="row"| %> <%= user.name %> <%= if rem(i + 1, 3) == 0 || + 1 == users_length, do: "</div>" %> <% end %>
Comments
Post a Comment