Django Templates

Django provides a convenient way to generate dynamic HTML pages by using its template system.

A template consists of static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted.

Why Django Template?

In HTML file, we can't write python code because the code is only interpreted by python interpreter not the browser. We know that HTML is a static markup language, while Python is a dynamic programming language.

Django template engine is used to separate the design from the python code and allows us to build dynamic web pages.

Django Template Configuration

To configure the template system, we have to provide some entries in settings.py file.

Here, we mentioned that our template directory name is templates. By default, DjangoTemplates looks for a templates subdirectory in each of the INSTALLED_APPS.

Django Template Simple Example

First, create a directory templates inside the project app as we did below.

django templates

After that create a template index.html inside the created folder.

django templates 1

Our template index.html contains the following code.

// index.html

Loading Template

To load the template, call get_template() method as we did below and pass template name.

//views.py

Set a URL to access the template from the browser.

//urls.py

Register app inside the INSTALLED_APPS

Run Server

Execute the following command and access the template by entering localhost:8000/index at the browser.

django templates 2

Django Template Language

Django template uses its own syntax to deal with variable, tags, expressions etc. A template is rendered with a context which is used to get value at a web page. See the examples.

Variables

Variables associated with a context can be accessed by {{}} (double curly braces). For example, a variable name value is rahul. Then the following statement will replace name with its value.

Django Variable Example

//views.py

//index.html

Output:

django templates 3

Tags

In a template, Tags provide arbitrary logic in the rendering process. For example, a tag can output content, serve as a control structure e.g. an "if" statement or a "for" loop, grab content from a database etc.

Tags are surrounded by {% %} braces. For example.


Next TopicURL Mapping




Latest Courses