Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask Template - For Loop Iteration key:value

I've got an HTML template with a Flask Jinja for loop in it which generates a table and looks like:

<tbody>
  {% for segment in segment_details %}
    <tr>
      <td>{{segment}}</td>
      <td>{{segment_details['{{segment}}']}}</td>
    </tr>
  {% endfor %}
</tbody>

I'm trying to iterate through a document of varying length/keys and present each row in the table as the key and value. In my Python code I've got this which has the desired response in the shell:

        for item in segment_details:
            print(item, segment_details[item])

But in Flask I get the item correctly listing all the rows but the

{{segment_details['{{segment}}']}}

Isn't producing any values, I've tried with and without the single quotes. Is this possible?

like image 812
Johnny John Boy Avatar asked Jul 18 '17 12:07

Johnny John Boy


2 Answers

This is where your error is:

<td>{{segment_details['{{segment}}']}}</td>

There is no need for the {{ }} inside. It should be just:

<td>{{segment_details[segment]}}</td>

For more see the documentation for Jinja. When you are writing a statement(if, for) in Jinja2 you use {% statement %} but when you are accessing a variable then just use {{ variable }}.

like image 65
kemis Avatar answered Nov 12 '22 13:11

kemis


it is a solution

<tbody>
  {% for key, segment in segment_details.items() %}
    <tr>
      <td>{{ key }}</td>
      <td>{{ segment }}</td>
    </tr>
  {% endfor %}
</tbody>
like image 13
Luis Carlos Herrera Santos Avatar answered Nov 12 '22 14:11

Luis Carlos Herrera Santos