Chandan Gupta
Chandan Gupta

Reputation: 1480

dynmacially generating href tags with jinja2 under flask

I referred to jinja2 for loop documentation but no luck generating following html dynamically.

     <li>
        <a href="#1"> This is the first sentence</a>
     </li>
     <li>
        <a href="#2">This is the senond sentence</a>
     </li>
     <li>
          <a href="#3">This is the third sentence</a>
     </li>
     <li>
          <a href="#4">This is the fourth sentence</a>
     </li>

Something like this should work:

{% for i in length %}
  <li>
     <a href="#{{i}}"> This is a sentence </a>
  </li>

where length changes every-time and is already predefined by a python script at background! here length = 4.

Upvotes: 2

Views: 484

Answers (2)

beebek
beebek

Reputation: 1947

What you are trying to do is iterate on non iterable object ie. on integer.

{% for i in range(1, length+1) %}
    <li>
        <a href="#{{ i }}">This is sentence {{ i }}.</a>
    </li>
{% endfor %}

This will work.

Upvotes: 2

Ajay
Ajay

Reputation: 4474

{% for i in range(1, length+1) %}
<li>
 <a href="#{{i}}"> This is a sentence </a>
</li>

should work

Upvotes: 1

Related Questions