Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir/Phoenix - for loop iterator in template

A certain number is passed from the controller to the template. For example, this number is 5. In the template, I need to display numbers from 1 to a given number (5). For example, in PHP this could be done like this:

for($i=1; $i<=given_number; $i++){
    echo $i;
}

Unfortunately, I can't figure out which is the best way to do this in Elixir/Phoenix. I would be grateful for your help.

like image 203
Денис Корх Avatar asked May 10 '26 07:05

Денис Корх


2 Answers

Using this code, I managed to solve the problem:

<%= for x <- 1..@number do %>
  <%= x %>
<% end %>
like image 151
Денис Корх Avatar answered May 14 '26 10:05

Денис Корх


If a HTML tag or a function component should be rendered for each @number, one can use the :for expression (here with a span as an example):

<span :for={x <- @number}>
  x
</span>

This is the same as

<%= for x <- 1..@number do %>
  <span><%= x %></span>
<% end %>
like image 25
jakobfp Avatar answered May 14 '26 09:05

jakobfp