Appending string to dictionary values using jinja template

Viewed 369

I have the following code for accessing the values in dictionary using jinja template

names={'ant':['abc',2456789,28-02-1991]}
{% for key,value in names.items %}
            {% for val in value %}
              <p class="lead">{{ val }} </p>
            {% endfor %}
{% endfor %}

For every value,it is printed I want to append a string.My values are "abc","2456789","28-02-1991".I want the following output:

Name:abc
Id:2456789
Date: 28-02-1991

How could I do it using jinja template?

2 Answers

You can use it like this with your current data structure.

{% for key, value in names.items %}
    <p class="lead">Name: {{ value.0 }}</p>
    <p class="lead">Id: {{ value.1 }}</p>
    <p class="lead">Date: {{ value.2 }}</p>
{% endfor %}

But it would be more readable if change your data structure into this:

my_dict = {
    'ant': {
        'id': 2,
        'name': 'abc',
        'date' : datetime.now()
    }
}

then your template would look like this:

{% for key, person in my_dict.items %}
    <p class="lead">Id: {{ person.id }} </p>
    <p class="lead">Name: {{ person.name }} </p>
    <p class="lead">Date: {{ person.date }} </p>
{% endfor %}

In Jinja-2 you can subscript in the variables:

{% for key,vals in names.items %}
    <p class="lead">Name: {{ vals[0] }}</br>
    Id: {{ vals[1] }}</br>
    Date: {{ vals[2] }}</p>
{% endfor %}
Related