Reputation: 9163
Good evening,
I'm trying to do a range function in a Jinja2 template and using the variable in a url_for function.
For example
{% for n in range(1, 6) %}
<a href="{{ url_for("static", filename="image[n].jpg") }}">Image {{n}}<a>
{% endfor %}
and I would like my output to be:
<a href="image1.jpg">Image 1</a>
<a href="image2.jpg">Image 2</a>
<a href="image3.jpg">Image 3</a>
<a href="image4.jpg">Image 4</a>
<a href="image5.jpg">Image 5</a>
<a href="image6.jpg">Image 6</a>
I was following this link: range in jinja2 inside a for loop
My output is as follows:
Image 6
Upvotes: 0
Views: 618
Reputation: 6735
In Jinja2, the +
operator concatenates strings. But that alone isn't enough, because n
is an integer, not a string. You have to cast it to a string as well.
This should do the trick:
{% for n in range(1, 6) %}
<a href="{{ url_for('static', filename='image ' + n|string + '.jpg') }}">Image {{n}}</a>
{% endfor %}
Upvotes: 1