Python Flask Rendering Template














































Python Flask Rendering Template



Flask Rendering Template


A template is a file that contains the text of a response, with placeholder variables for the dynamic parts that will be known only in the context of a request. The process that replaces the variables with actual values and returns a final response string is called rendering. For the task of rendering templates, Flask uses a powerful template engine called Jinja2.

Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if its a package its actually inside your package




Template




Code




Output





The function render_template provided by Flask integrates the Jinja2 template engine with the application. This function takes the filename of the template as its first argument. Any additional arguments are key/value pairs that represent actual values for variables referenced in the template. In this example, the second template is receiving a name variable. 

Keyword arguments like name=name in the previous example are fairly common but may seem confusing and hard to understand if you are not used to them. The 'name' on the left side represents the argument name, which is used in the placeholder written in the template. The 'name' on the right side is a variable in the current scope that provides the value for the argument of the same name.


Variable


The {{ name }} construct used in the template shown in Example 3-2 references a variable, a special placeholder that tells the template engine that the value that goes in that place should be obtained from data provided at the time the template is rendered. Jinja2 recognizes variables of any type, even complex types such as lists, dictionaries and objects. The following are some more examples of variables used in templates


Filters




Variables can be modified with filters, which are added after the variable name with a pipe character as separator. For example, the following template shows the name variable capitalized




Comments