Templates and static files in flask

Mega flask tutorial

Introduction

Templates and static files helps on various aspects of web development.

In previous tutorial, we learned how to run a hello world program in flask but the way we used in the tutorial, can not be used in large projects.

Why templates?

While working on large projects, we need to render large html codes in the browser and if we just return the html code in the previous way then it become very difficult to work with it. Therfore, we save the html code in html files and render in the flask app with the help of Jinja template engine.

So in this tutorial, we will see how to use templates and static files in flask.

Rendering templates

In order to render templates, you need to create a templates subfolder in which you can store templates. By default, the Flask looks for templates in a templates subfolder located inside the applicaion folder.

Here is the code for rendering the templates in Flask.

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("home.html")

if __name__=="__main__":
    app.run(debug=True)

To render templates, we use render_template function. This render_template function integrates the Jinja2 template engine with the application. It takes the filename (template name) as its first argument.Any additional arguments are key/value pairs that represent actual values for variables referenced in the template.

Using variables in templates

Let's understand the usage of variables in template with the help of example.

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def home():
    name = "Sam"
    return render_template("home.html", name=name)

if __name__=="__main__":
    app.run(debug=True)

In the above code, we add an additional argument name which we will use in our template home.html.

Here is the html code of Home.html.

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Home</title>
</head>

<body>
    <h1> Hello {{ name }} </h1>
</body>

</html>

The {{ name }} construct used in the template references a variable that tells the template engine that value of name variable (the addional argument) should be placed here.

Jinja2 can recognize variables of any type. It can recognize complex types such as lists, dictionaries and objects. Following are some more examples of variables used in templates.

<p>A value from a dictionary: {{ mydict['key'] }}.</p>
<p>A value from a list: {{ mylist[3] }}.</p>
<p>A value from a list, with a variable index: {{ mylist[myintvar] }}.</p>
<p>A value from an object's method: {{ myobj.somemethod() }}.</p>

Static files

In order to make the site more attractive, we need static files. A powerful application cannot be useful without static files like javascript, images and CSS.

To use static files in application you need to create a static subfolder which we store static files.

After that, you need to call url_for('static', filename='css/styles.css', _external=True) which will return localhost:5000/static/css/styles.css.

Let's say that you want to load static file favicon.ico in your HTML template. You will insert the following block of code in your template.

<link rel="icon" href="{{ url_for('static', filename = 'favicon.ico') }}"
 type="image/x-icon">

Thanks

Read the full article Templates and Static files in Flask