Passing data to html templates in flask

Passing data to html templates in flask

Source code

[sourcecode] #passing data/variables to html templates
#Lets import flask first
from flask import Flask
#Lets import Render_templates
from flask import render_template
#Lets create an app now
app = Flask(__name__)
#lets create our first route
@app.route(‘/’)
#lets create a function for our route
def index():
#Now I am creating a variable and I will pass it to my html template
name = "gul khan"
return render_template(‘index.html’, name=name)
#name = name is the data I want to pass
#Now I will create function to run app
app.run(debug=True, port=8080)
#Now I will create a template folder and inside it a html file
# Then I will display my data/name sent from backend.
[/sourcecode]

Source Code of HTML Template

[sourcecode]

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask Tutuorial</title>
</head>
<body>
<!– I am going to use {{my_variable_here}} to show my data –>
<h1>Hello {{name}}</h1>
<p>Welcome to my blog.</p>
<!– Lets run the App –>
</body>
</html>

[/sourcecode]

Final Words

Passing data to html templates in flask

HTML Template explaination

In this tutorial we are goig to learn how to pass data to HTML template.

You need to create a templates folder.

Inside templates folder, you need to create a HTML file.

We will use jinga templates in our flask app.

w use double brackets {{}} to display a variable.

Let suppose I want to show my name.

It will be like {{name}}

Here name is the variable, I want to display.

I can pass anything in name from backend.

Flask server

You need a simple flask server.

Create a simple route with get method.

now you need to create a variable like this

nameVar = “gul khan”

Now I will return and render a html template like below.

return render_template(‘index.html’, name = nameVar)

Now you need to run your app

app.run()

if you want to use debug mode

app.run(debug=True)

if you want to use a specific port

app.run(port=8080)

Github link is here

 

FEEL FREE TO COMMENT BELOW. HAVE A GREAT DAY.

Tony BB
 

TonyBB is a Coach , marketer, hypnotist and a founder of RSKVF Production who specializes in providing simple, affordable, and easy to use solutions for Life.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: