Ashwani
Ashwani

Reputation: 37

How to use rendered data using jinja in rendered template but without showing it in html page?

{% for item in dlist %}
      <p>{{ item }}</p>
{% endfor %}

{% for i in range(dlist|length) %}
    {{ dlist.pop(0) }}
{% endfor %}

After using the list "dlist", I want to clear the data on it it so that upon next iteration the list starts from size 0. But if I do it this way upon using dlist.pop(0), the data is being printed on my html page and I don't want that. How can I do that?

Upvotes: 1

Views: 354

Answers (1)

arshovon
arshovon

Reputation: 13661

If you want to clear the list completely, you can clear the list using clear() method. Details of the method can be read from the official documentation.

The {{}} delimiter will display the result even if it is None value. We need to block it as we want to clear the list only and we do not want to show None after executing it. I have added a condition inside the delimiter to hide the None from output.

app.py:

from flask import Flask, render_template


app = Flask(__name__)

@app.route("/", methods=["GET"])
def home():
    dlist = ["Ahmedur", "Rahman", "Shovon", "arsho"]
    return render_template("data.html", dlist=dlist)

data.html:

{% for item in dlist %}
    <p>{{ item }}</p>
{% endfor %}

{{ dlist.clear() if dlist.clear()}}

<hr>

{% for item in dlist %}
    <p>{{ item }}</p>
{% endfor %}

Output:

clear list in jinja2 template

The second for loop after the hr tag is not showing any value in the output. Because dlist doesn't contain any value after the execution of clear() method.

Upvotes: 1

Related Questions