Question

I have loop in Twig template:

{% for item in 1..0 %}
     {{ item }}
{% endfor %}

(of course in real life instead of 0 there is variable value). I would expect in this example that loop won't be executed because 0 is lower than 1. But in fact it displays

1 0 

Question: is there any way in this example using simple for loop in Twig (or other loop) to tell Twig I want to iterate ++ not -- or I have to add condition to check before loop if 0 is lower than 1

EDIT:

Of course I'm aware I can create array in PHP and use it in Twig template but what about this case - without creating array in PHP

EDIT2:

I want it simple use for generating star rating. Now I need to have code because I had to add extra if checking for each for loop:

{%  if full_stars_number >= 1 %}
    {%  for item in 1..full_stars_number %}
       <img src="img/full_star.png" />
    {% endfor %}
{% endif %}
{%  if half_stars_number >= 1 %}
    {%  for item in 1..half_stars_number %}
       <img src="img/half_star.png" />
    {% endfor %}
{% endif %}
{%  if empty_stars_number >= 1 %}
    {%  for item in 1..empty_stars_number %}
       <img src="img/empty_star.png" />
    {% endfor %}
{% endif %}
Was it helpful?

Solution

Try this:

{%  for item in 1..full_stars_number if full_stars_number>0 %}
   <img src="img/full_star.png" />
{% endfor %}

{%  for item in 1..half_stars_number if half_stars_number>0 %}
   <img src="img/half_star.png" />
{% endfor %}

{%  for item in 1..empty_stars_number if empty_stars_number>0 %}
   <img src="img/empty_star.png" />
{% endfor %}

This is basically the same as what you already did in your EDIT2, but in a slightly more concise way.

OTHER TIPS

1..x generates a collection, with inclusive values. It can be ordered ascending or descending. This is expected.

I'm not sure what you are trying to achieve, but the way you described it is not possible in twig out of the box.

You could write your own twig function, which would generate the values, or return an empty array:

{% set itemsCount = 0 %}
{% for item in my_crazy_function(itemsCount) %}
    {{ item }}
{% endfor %}

Edit:

If you simply want to repeat a value number of times you could write a twig filter:

{{ '<img src="img/empty_star.png" />' | repeat(5) }}

A function implementation could just be a call to PHP's str_repeat:

class Project_Twig_Extension extends Twig_Extension
{
    public function getFilters()
    {
        return array(
            new Twig_SimpleFilter('repeat', 'str_repeat'),
        );
    }

    // ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top