To build and insert data into HTML page, Django uses Jinja2 template engine as its default template engine. If we know already Jinja2 template language, we do not need to learn anything about this template, just build templates we need. 

 

Jinja2 template language is very rich. It also allows us to design template following the Object Oriented Programming  (OOP) concept. It means that we can use template inheritance concept in designing Django templates. However, we are not forced to use this concept, we have a choice to use the easy parts of this template language if we want.

 

In fact, Jinja2 template language is composed of variable and statements such if and for loop, but this language is heavily inspired by Python programming language. As the result, if you already know Python, you will pickup Jinja2 template language very fast. 

 

To start, variable in Jinja2 template language comes from Python variable that we pass to parameter ‘context’ in render( ) method in views.py module.

 

#home/views.py
from django.shortcuts import render

# Create your views here.
def index(request):
    kdict = {
        'siteTitle':'Khmer Web',
        'pageTitle': 'Home',
        'message': 'ស្វាគមន៍​មក​កាន់​ទំព័រ​ដើម!'
    }
    
    return render(request,'base.html',context={'data':kdict})

 

<!--home/templates/base.html-->
{% load static %}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <title>{{ data.siteTitle }} | {{ data.pageTitle }}</title> 
        <link rel="stylesheet" href="{% static 'styles/base.css' %}" />
        <link rel="stylesheet" href="{% static 'fonts/setup.css' %}" />
        <link rel="icon" href="{% static 'images/siteLogo.png' %}" />
    </head>
    <body>
        <p>{{ data.message }}</p>
    </body>
</html>

 

To insert data into HTML page, we use {{ }} sign to include the value of the variable sent by the handler through render( ) method. Most of the time, the variable is a regular Python dictionary object for which we have to use Python dictionary key to get the value.

 

GitHub: https://github.com/Sokhavuth/khmerweb-django

Heroku: https://khmerweb-django.herokuapp.com