Flask Tutorial – Template Variables in Flask

In this Flask Tutorial iam going to talk about Template Variables in Flask .

so sometimes we need to send data from our flask views to the html files, for this purpose

you can use template variables. for example sometimes we need to send data from our

flask views to the database. now in this example we are not going to use the data from the

database, we are going to just send some predefined data from our index view to the index.html.

 

 

 

If you are interested in Web Development with Django Framework, than you can read the

complete articles in this link,  Django Web Development Tutorials.

 

 

 

OK now this is our app.py file, we  are going to just bring changes in our index view, because we want to send some data from index view to our index.html.

 

So you can see that 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.

And the second one is the data that we want to send for index.html file, and you can see that i have sent just a simple predefined name value to my html file.

 

 

 

 

 

Now we want to get this data in our index.html, so these are our html files.

 

templates/base.html

 

 

 

 

templates/index.html

 

You can see that in the bottom we have used {{}} placeholder to get the data from our index view, this is 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. 

 

 

 

 

 

templates/contact.html

 

 

 

 

Template Variables Filters in Flask

Also there are different filters that you can use with Template Variable like this.

 

 

 

 

Variable Filters

Name Description 
safe Renders the value without applying escaping
capitalize Converts the first character of the value to uppercase and the rest to lowercase
lower Converts the value to lowercase characters
upper Converts the value to uppercase characters
title Capitalizes each word in the value
trim Removes leading and trailing whitespace from the value
striptags Removes any HTML tags from the value before rendering

 

 

 

 

So now if you run the project, this will be the result 

 

 

 

 

http://localhost:5000/

Flask Tutorial - Template Variables in Flask
Flask Tutorial – Template Variables in Flask

 

 

 

 

 

Also you can watch my complete 4 hours training on Flask Web Development

Subscribe and Get Free Video Courses & Articles in your Email

 

Share via
Copy link
Powered by Social Snap
×