Templates - In Flask


Templates are the structure of a website. Here in Python Flask. templates are treated as the views, which means these files are kept in separate folder, which will be dedicated to the UI elements, which we call templates.

 If we write the following code

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
   return '<html><body><h1>'Hello World'</h1></body></html>'

if __name__ == '__main__':
   app.run(debug = True)


we will get an output as an H1 tag element in the browser, which means that the return functionality can interpreter the HTML data. But the issue is, when we have a huge set of coding and that too with multiple variables being called inside the view, to show dynamic data on the page, we will have to move in and out many times. 

This is where the jinja2 comes in picture. jinja2 is a templating engine which helps in showing templates with dynamic data over Python.

The Flask is based on jinja2 templating engine, that is why its easy to return entire template as an output. The rendering of templates can be done using the render_template() function.

Have a look at the below example:

rom flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
   return render_template(‘hello.html’)

if __name__ == '__main__':
   app.run(debug = True)

Here the entire hello.html file is passed as an argument in the render_template() function, which will be treated as a template to be rendered when user requests for the root page.

Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present.
  • Application folder
    • Hello.py
    • templates
      • hello.html
As we talk about the  web templating system, we refer to designing an HTML script in which the variable data needs to be dynamically inserted. Web template system is made up of template processor, template engine and some data source.

jinja2 is used by Flask as its templating engine. HTML syntax contains placeholders for variables and expressions which are replaced by values when the template is rendered.


The following code is saved as hello.html in the templates folder.

<!doctype html>
<html>
   <body>
   
      <h1>Hello {{ name }}!</h1>
      
   </body>
</html>


Next, run the following script from Python shell.

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/<user>')
def hello_name(user):
   return render_template('hello.html', name = user)

if __name__ == '__main__':
   app.run(debug = True)

As the development server starts running, open the browser and enter URL as − http://localhost:5000/hello/Vikash

You will see the output as 

Hello Vikash


The following delimiters are used to escape from HTML in jinja2
  • {% ... %} for Statements
  • {{ ... }} for Expressions to print to the template output
  • {# ... #} for Comments not included in the template output
  • # ... ## for Line Statements

Have a look at the example below, we have used a conditional statement in the template to show some data. The hello() function will accept the integer parameter in the URL rule, which will be passed to the hello.html template. Where it's value will be compared with 50, and the rendering will be done accordingly.

The Python Script is as follows −


from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/<int:score>')
def hello_name(score):
   return render_template('hello.html', marks = score)

if __name__ == '__main__':
   app.run(debug = True)



HTML template script of hello.html is as follows −

<!doctype html>
<html>
   <body>
   
      {% if marks>50 %}
      <h1> Your result is pass!</h1>
      {% else %}
      <h1>Your result is fail</h1>
      {% endif %}
      
   </body>
</html>


You might have noticed a few things, like the conditional statements are enclosed in {%. %}
Run the Python script and visit URL http://localhost/hello/60 and then http://localhost/hello/30 to see the output of HTML changing conditionally.

Python loop constructs can also be employed inside the template. In the following script, the result() function sends a dictionary object to template results.html when URL http://localhost:5000/result is opened in the browser.

The Template part of result.html employs a for loop to render key and value pairs of dictionary object result{} as cells of an HTML table.

Run the following code from Python shell.

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/result')
def result():
   dict = {'phy':50,'che':60,'maths':70}
   return render_template('result.html', result = dict)

if __name__ == '__main__':
   app.run(debug = True)
Save the following HTML script as result.html in the templates folder.
<!doctype html>
<html>
   <body>
   
      <table border = 1>
         {% for key, value in result.iteritems() %}
         
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
            
         {% endfor %}
      </table>
      
   </body>
</html>

Here, again Python statements corresponding to the For loop are enclosed in {%..%} whereas, the expressions key and value are put inside {{ }}.

After the development starts running, open http://localhost:5000/result in the browser to get the output as a table.

Now as you have learnt about the templates and the way of rendering data inside the template move ahead to the following tutorials to learn more ..

Comments

Popular Posts