Skip to content

[Python] Flask Study Notes (2): Use render_template to Render HTML

Last Updated on 2021-06-29 by Clay

When we using Flask framework to develop a web page, we can use render_template() function to render html web page.

render_template() allows us to call the html file that has been written through Flask. These html files must be placed in the templates folder prepared in advance. Below we will implement a simple example.


templates folder

If you want to make a simple program that uses render_template() to call html file, then the relative path between your python file and html file should be as shown below:

  • flask_render_template.py: It is a file that processing the backend functions
  • templates folder: It contains the html file idnex.html that you want to render

When using the render_template() function, it will automatically find the html file in the templates folder.


index.html

<body style="background-color: black">
     <p style="color: white">Hello {{ Name }}!</p>
</body>



Output:

When I write HTML here, I used curly braces {{ }} to assign values to variables. This is the syntax of Jinja2. The grammar of Jinja2 is consistent with the core template grammar of Flask, after all, the developers are the same person.

So we can see here that simply opening the HTML file directly will only see the ugly “{{ Name }}”. After all, HTML does not understand what this is; but this parameter will be useful in the Flask file after a while.

It is worth noting that the web page currently renders the style I set perfectly: the background is black and the text is white.


flask_render_template.py

# -*- coding: utf-8 -*-
from flask import Flask, render_template


app = Flask(__name__)


@app.route('/')
def main():
     return render_template('index.html')


if __name__ == '__main__':
     app.run(host='127.0.0.1', port=8000)



Output:


The first thing to remember: Import the render_template() function.

from flask import Flask, render_template



Then you can see that the {{ Name }} we set is gone! This is because we currently have not given us any parameters for the rendered template. But so far, HTML rendering has been very successful, and you can see that the background is black and the string is white.

Then, we can also assign a value to the Name parameter.

# -*- coding: utf-8 -*-
from flask import Flask, render_template


app = Flask(__name__)


@app.route('/')
def main():
     return render_template('index.html', Name='World')


if __name__ == '__main__':
     app.run(host='127.0.0.1', port=8000)



Output:

Just set the variables after the render_template() function. Isn’t it convenient?


References


Read More

Leave a Reply