DEV Community

loading...
Cover image for Django Templates - Short introduction and FREE samples

Django Templates - Short introduction and FREE samples

sm0ke profile image Sm0ke Updated on ・7 min read

Hello Coders,

This article presents a short introduction to Django Template system, a modern and designer-friendly language for Python, used to generate dynamic pages by Django Framework. To make this article more useful, I will present at the end a short-list with open-source Django Templates available for download directly from Github. For newcomers, Django is a Python Web framework built by experienced developers that encourages rapid development.


Thank you! Content provided by AppSeed - App Generator.



What is Django

Django Framework, created initially in 2003 as a private project by a press agency, becomes an open-source project in 2008 managed by Django Software Foundation.

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel.

Using Django, developers can build websites, APIs, microservices on top of all libraries and packages provided in the Python ecosystem.

For newcomers, a Framework comes with modules and features usable in many projects: authentication, database interfaces, our TEMPLATE system for instance.

Being such a powerful framework, Django provides a template engine used to render pages in the browser with ease by reusing components, injecting dynamic content, extend templates, filter displayed information, and much more.

Let's take one at a time and reveal a few basic features provided by the Django Template engine.


Django Templates configuration

Templates are loaded and processed by Django from the folder specified in settings.py.

# settings.py Sample
...
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, 'core/templates')
...
)
Enter fullscreen mode Exit fullscreen mode

From now on, we will assume the files and templates are saved in core/templates directory.


Render simple HTML

At this point, Django knows where to look for a templated referred in a controller, and we can define a first, super simple template.

File Location/Name: core/templates/index.html

index.html contents

<html>
  <head>
    <title>
      First Django Template
    </title>
  </head>
  <body>
    <h1>
      My template
    </h1>
    <p>
      some content here
    </p>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

The controller

from django.shortcuts import render

# View for index page. 
def index(request):
  return render(request, 'index.html')
Enter fullscreen mode Exit fullscreen mode

If we access the page in the browser, we will notice that the template has been taken into account by the view.


Use variable in the template

The previous sample use hardcoded information for page title, H1 tag, and the content paragraph. We can change this limitation with ease by using a variable that might come from the database or from the user. Let's update our code to use a variable for the page title.

File Location/Name: core/templates/index.html

index.html contents

<html>
  <head>
    <title>
      {{ title }} 
    </title>
  </head>
  <body>
    <h1>
      My template
    </h1>
    <p>
      some content here
    </p>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

The controller

from django.shortcuts import render

# View for index page. 
def index(request):
  title = "My new title"
  return render(request, 'index.html', { "title": title ) } )
Enter fullscreen mode Exit fullscreen mode

The render() method expects a dictionary where the keys are variables names and values and .. the values injected in the template. Once rendered by the Django Template engine, our HTML becomes:

<html>
  <head>
    <title>
      My new title
    </title>
  </head>
  <body>
    <h1>
      My template
    </h1>
    <p>
      some content here
    </p>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

More use-cases

Django template system allows us to have more than simple variable replacement in our templates: loops, set up filters, conditionals.


Conditional statements

To use a conditional statement in a template file we must use another syntax compared to the usage of a variable:

  • variables {{ variable }}
  • conditionals { % if whatever % }

Let's take a look at a real sample:

<span>
  { % if years <10 % }
    Child ...
  { % elif years < 18 % }
    Teenager ...
  { % else % }
    Adult ...
  { % endif % }
</span>
Enter fullscreen mode Exit fullscreen mode

The controller

from django.shortcuts import render

# View for index page. 
def index(request):
  years = 15
  return render(request, 'index.html', { "years": years) } )
Enter fullscreen mode Exit fullscreen mode

The rendered version by Django is shown below:


< span >
    Teenager ...
</span >

Enter fullscreen mode Exit fullscreen mode

Looping in a template

Looping allows you to read or iterate through the elements of a data dictionary. In the controller, we sent a list with numbers. To see numbers on the rendered page we will use a for structure.

<ul>
  {% for number in my_array %}
    <li>
      {{ number }}
    </li>
  {% endfor %}
</ul>
Enter fullscreen mode Exit fullscreen mode

The controller

from django.shortcuts import render

# View for index page. 
def index(request):
  my_array = [1,2 3]
  return render(request, 'index.html', { "my_array": my_array) } )
Enter fullscreen mode Exit fullscreen mode

The rendered version by Django is shown below:

< ul >
    < li > 1 </ li >
    < li > 2 </ li >
    < li > 3 </ li >
</ ul >
Enter fullscreen mode Exit fullscreen mode

Extending the templates

This feature allows us to extend or reuse a master page template by injecting on the specific content of the current context.

A simple and intuitive use case might be a home page and contact page where the footer and top menus are identical and only the main content is different. Let's design a template and sample pages to explain the concept:


Define a master template called base.html

Parent HTML - saved as base.html

<html>
  <head>
    <title>My {% block title %}{% endblock %} </title>
  </head>
  <body>
    <div class="container">
      <h2>This is from the base template</h2>
      <br>
      { block content }{ endblock }
      <br>
    </div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Define the HOME page

The Child template - saved as home.html

{ extends "base.html" }

{ block title } Homepage { endblock }

{ block content }
  Home page content
{ endblock }
Enter fullscreen mode Exit fullscreen mode

When Django loads home.html, the { extends } block informs the engine to merge the base.html template with the content provided by home.html.

  • { block title } becomes Homepage
  • { block content } becomes Home page content

Generated HTML

<html>
  <head>
    <title>Homepage</title>
  </head>
  <body>
    <div class="container">
      <h2>This is from the base template</h2>
      <br>
      Home page content
      <br>
    </div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

This feature called Template Inheritance helps us to win time by reusing components and build paged dynamically with ease.

Django template engine offers much more than this. I will mention only a few more features below. The full information can be found in the official documentation: Django Template System


To apply the theory, we can play with a few FREE samples published on Github under the MIT license.


Django Datta Able

Admin Dashboard coded in Django Framework on top of Datta Able, a modern Bootstrap 4 dashboard template. The Django codebase is provided with authentication, database, ORM and deployment scripts.



Django Datta Able - Open-Source Admin Panel Coded in Django.


Django Template Volt

Open-Source Django Dashboard coded with basic modules, database, ORM, and deployment scripts on top of Volt Dashboard (free version), a modern Bootstrap dashboard design.

Volt is a free and open-source Bootstrap 5 Admin Dashboard featuring over 100 components, 11 example pages and 3 customized plugins. Volt does not require jQuery as a dependency meaning that every library and script's are jQuery free.



Django Dashboard Volt - Template project provided by AppSeed.


Django Template Argon

Open-Source dashboard coded in Django with basic modules, authentication, and deployment scripts.

The UI (Argon Dashboard) is built with over 100 individual components, giving you the freedom of choosing and combining. All components can take variations in color, that you can easily modify using SASS files.



Django Dashboard Argon - Template project provided by AppSeed.


Django Atlantis Dark

Atlantis Lite is a free bootstrap 4 admin dashboard that is beautifully and elegantly designed to display various metrics, numbers or data visualization. This open-source admin dashboard has 2 layouts, many plugins and UI components.



Django Template - Atlantis Dark, free template provided by AppSeed.


Resources & Links


Thank you! Btw, my (nick) name is Sm0ke and I'm pretty active also on Twitter.

Discussion (0)

pic
Editor guide