Templating in Flask. ๐Ÿพ

ketanip

KetanIP

Posted on October 6, 2020

Templating in Flask. ๐Ÿพ

Basics

Templating in flask is super simple. Flask uses Jinja templating engine. We render templates using render_template() function in flask. Here is a example,

from flask import render_template

@app.route('/template-view')
def templateView():
    render_template("template_name.html")

Enter fullscreen mode Exit fullscreen mode

We need to keep out all the templates in templates directory. You may nest in with other directories if you want.

Passing Data into Template

Now we will learn how to pass data into the template from the flask view.

from flask import render_template

@app.route('/template-view-with-varible')
def templateView():
    name = 'Ketan'
    render_template("template_name.html", { "name" : name })

Enter fullscreen mode Exit fullscreen mode

We need to pass the data in template with the use of dictionary.
In template we can access this data by,

<h1>Hello {{ name }}!</h1>
Enter fullscreen mode Exit fullscreen mode

In next blog we will learn how to use template literals.

Read it on my website Templating in Flask. - Flask For Noobs ๐Ÿงช - Part 2.

Also Read Using Template engine in Flask - Flask For Noobs ๐Ÿงช - Part 3 .

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
ketanip
KetanIP

Posted on October 6, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About