Basics of Django templates

Reading Time : ~ .

Django template engine comes as part of django framework and its very easy, extensible and handy to develop complex web applications with simplest efforts. Lets see basics of django template engine.

Basics:

A template is a text document, or a normal Python string, that is marked-up using the Django template language. Template system in Python can be used in the following way:

First, compile the raw template code into a Template object.
Then, call the render() method of the Template object with a given context.

Rendering a context: Once you have a compiled Template object, you can render a context or multiple contexts with it. We have a Context class at django.template.Context, and its constructor takes two (optional) arguments:
    1. A dictionary mapping variable names to variable values.
    2. The name of the current application.

Example:

from django.template import Template, Context

# Creating a Template object by instantiating it and its constructor takes 
one argument i.e., raw template code.
template = Template("My name is {{my_name}}")   
context = Context({"my_name":"XXX"})

# Calling the Template object's render() method with the context to fill the template.
template.render(context)

Templates:

A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, etc.). A template contains variables, which get replaced with values when the template is evaluated, and tags, which control the logic of the template.

The following example illustrates a few basics.


{% extends "base.html" %}
{% block title %}{{ section.title }}{% endblock %}

{% block content %}
  <h1>{{ section.title }}</h1>
  {% for story in story_list %}
    <h2>{{ story.headline|upper }}</h2>
    <p>{{ story.description|truncatewords:"100" }}</p>
  {% endfor %}
{% endblock %}

The above template extends another template called "base.html". And this template provides content for the blocks defined in the "base.html" template. Each element is described below.

Variables:

Variables look like this: {{ variable }}. When the template engine encounters a variable, it evaluates that variable and replaces it with the result. Variable names consist of any combination of alphanumeric characters, underscore ("_"), dot (".") except spaces and punctuation characters. The dot (".") has a special meaning i.e., to access attributes of a variable.

In the above example, {{ section.title }} will be replaced with the title attribute of the section object.

Note: If you use a variable that doesn’t exist, the template system will insert an empty string by default.

Filters:

By using filters, you can modify the variables for display. Django provides about thirty built-in template filters. Most commonly used template filters are:

♦ lower - Example: {{ name|lower }} - This displays the value of the {{ name }} variable after being filtered through the lower filter, which converts text to lowercase. Use a pipe (|) to apply a filter.

♦ truncatewords - Some filters take arguments. A filter argument looks like this: {{ bio|truncatewords:30 }}. This will display the first 30 words of the bio variable.

♦ default - If a variable is false or empty, use given default. Otherwise, use the value of the variable.

For example: {{ value|default:"nothing" }}

If value isn’t provided or is empty, the above will display “nothing”.

Tags:

Tags look like this: {% tag %}. Tags are more complex than variables: Some create text in the output, some control flow by performing loops or logic, and some load external information into the template.

Some tags require beginning and ending tags (i.e. {% tag %} ... tag contents ... {% endtag %}).

Django provides about twenty built-in template tags. Here are some of the more commonly used tags:

♦ for - Loop over each item in an array. In the above example, to display a list of stories provided in story_list we have used a for loop.

♦ if, elif, and else - Evaluates a variable, and if that variable is “true” the contents of the block are displayed:

Example:

  {% if story_list|length > 2 %}
    Number of stories: {{ story_list|length }}
  {% elif story_list|length == 1 %}
    There is only one story!
  {% else %}
    No stories.
  {% endif %}

Comments:

To comment-out part of a line in a template, use the comment syntax: {# #}.

For example, this template would render as 'hello':  {# greeting #}hello

Template inheritance:

The most powerful and the most complex part of Django’s template engine is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. It’s easy to understand template inheritance by starting with an example:

    <html lang="en">
      <head>
        <link href="style.css" rel="stylesheet" />
        <title>Home Page</title>
      </head>
      <body>
        <div id="content">
          {% block content %}{% endblock %}
        </div>
      </body>
    </html>

This template, which we’ll call base.html, defines a simple HTML skeleton document. It’s the job of “child” templates to fill the empty blocks with content. The example below Templates topic shows child template.

The extends tag is the key here. It tells the template engine that this template “extends” another template. When the template system evaluates this template, first it locates the parent – in this case, “base.html”.

At that point, the template engine will notice the two block tags in base.html and replace those blocks with the contents of the child template. Depending on the value of story_list, the output might look like:

    <html lang="en">
      <head>
        <link href="style.css" rel="stylesheet" />
        <title>Story List</title>
      </head>
      <body>
        <div id="content">
          <h2>STORY ONE</h2>
          <p>This is first story.</p>
          <h2>STROY TWO</h2>
          <p>This is second story.</p>
        </div>
      </body>
    </html>
    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Django - Database access optimization Ashwin Kumar

Django - Database access optimization, Django Queryset is generally lazy in nature. It will not hit the database until it evaluates the query results.

Continue Reading...
Introduction to API development with Django REST framework Ashwin Kumar

Introduction to API development with Django REST framework. You can build the API for any Django application. Pre-requisites are Django and OOPS(object oriented programming concepts) ...

Continue Reading...
Export html web page to pdf using jspdf Chaitanya Kattineni

jsPDF is used to generate pdf files in client-side Javascript. You can find the links for jsPDF here and also you can find the link ...

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties