Home » Python

For loop in Flask template engine

Python Flask: In this tutorial, we are going to learn about the for loop in the Flask Template Engine in Python with examples.
Submitted by Sapna Deraje Radhakrishna, on October 16, 2019

Flask comes with a Jinja templating language. The template essentially contains variables as well as some programming logic, which when evaluated are rendered into HTML with actual values. The variables and/or logic are placed between tags or delimiters.

Jinja templates are HTML files which by flask conventions are placed in the templates folder in the Flask project.

Having a loop of the list of users or any list as a matter is a very obvious requirement in a web application. It would be very naïve and unmanageable to add a new page for every new item in the list. Here is where the for-loop in the jinja templates are useful.

Consider the following example,

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/jinja")
def jinja_test():
    return render_template('include_help.html', my_string="Include Help!", my_list=[0,1,2,3,4,5])
  
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5005)

In the above example, when in the browser the user navigates to http://localhost:5005/jinja the rendered web page will sequentially display the list number.

The list could as simple as a list of numbers or users or profiles to make it complex.

The 'include_help.html' is implemented as

<html>

<head>
    <title>Include help Template Example</title>
</head>

<body>
    <p>{{my_string}}</p>
    <p>Your lucky number is ;) : {{my_list[3]}}</p>
    <p>Loop through the list:</p>
    <ul>
        {% for n in my_list %}
        <li>{{n}}</li>
        {% endfor %}
    </ul>
</body>

</html>

On rendering of the template, the my_string and my_list is replaced with the actual values sent from the backend code. The my_list is then iterated using a for loop. The for loop starts with a for and ends with endfor inside the {%%} tag.

On running the above code, the html rendered is,

for loop in Python flask







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.