app-generator / docs

App Generator - The Official Documentation | AppSeed
https://docs.appseed.us
1 stars 1 forks source link

Django Templates and Template System #69

Open mahfujul-helios opened 8 months ago

mahfujul-helios commented 8 months ago

Django Templates and Template System

Templates

Templates in Django are text files that define the structure and layout of HTML pages. They include placeholders, called template tags and template filters, which allow you to insert dynamic content generated by your views and models. Templates are designed to be markup-friendly, allowing you to write HTML code with minimal syntax overhead.

Template System

The Django template system is responsible for rendering templates and generating the final HTML response. It consists of several components:

  1. Template Engine: The core component that parses and renders templates, interprets the template syntax, executes template tags and filters, and generates the final HTML output.

  2. Template Tags: Django-specific syntax elements that control the rendering flow and logic within templates, such as iteration, conditional rendering, and variable assignment.

  3. Template Filters: Used to modify or transform the value of variables before rendering them in the template, such as string formatting, date manipulation, or data filtering.

  4. Template Inheritance: Allows you to create a base template with common elements and extend it in multiple child templates, promoting code reuse and consistent layout across different pages.

  5. Template Loaders: Responsible for locating and loading templates from various sources, such as the filesystem or Django's app directories.

  6. Template Context: A dictionary-like object that contains the data passed from the view to the template, providing the variables and data that can be accessed and rendered within the template.

The template system offers several advantages:

By leveraging Django's template system, developers can create dynamic and maintainable web applications with a clear separation between presentation and logic, promoting code organization and collaboration between designers and developers.

mahfujul-helios commented 8 months ago

Django Templates and Template System

Templates are the third and most important part of Django’s MVT Structure. A template in Django is basically written in HTML, CSS, and Javascript in a .html file. Django framework efficiently handles and generates dynamic HTML web pages that are visible to the end-user. Django mainly functions with a backend so, in order to provide a frontend and provide a layout to our website, we use templates. There are two methods of adding the template to our website depending on our needs. We can use a single template directory which will be spread over the entire project. For each app of our project, we can create a different template directory.

Configuration settings.py: Django Templates can be configured in app_name/settings.py,

TEMPLATES = [ 
    { 
        # Template backend to be used, For example Jinja 
        'BACKEND': 'django.template.backends.django.DjangoTemplates', 
        # Directories for templates 
        'DIRS': [], 
        'APP_DIRS': True, 

        # options to configure 
        'OPTIONS': { 
            'context_processors': [ 
                'django.template.context_processors.debug', 
                'django.template.context_processors.request', 
                'django.contrib.auth.context_processors.auth', 
                'django.contrib.messages.context_processors.messages', 
            ], 
        }, 
    }, 
] 

**Using Django Templates**

Illustration of How to use templates in Django using an Example Project. Templates not only show static data but also the data from different databases connected to the application through a context dictionary. Consider a project named appseed having an app named seed

views.py: To render a template one needs a view and a URL mapped to that view. Let’s begin by creating a view in seed/views.py, 

simple_view: Renders the “geeks.html” template with the data “Gfg is the best.”
check_age: Handles a form submission, checking the user’s age and rendering the “check_age.html” template with the age.
loop: Sends a list of numbers and the string “Gfg is the best” to the “loop.html” template.

```python
from django.shortcuts import render 
from .forms import AgeForm 

# create a function 
def simple_view(request): 
    data = {"content": "Gfg is the best"} 
    return render(request, "geeks.html", data) 

def check_age(request): 
    if request.method == 'POST': 
    # Get the age from the form 
        age = int(request.POST.get('age', 0)) 
        return render(request, 'check_age.html', {'age': age}) 
    return render(request, 'check_age.html') 

def loop(request): 
    data = "Gfg is the best"
    number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
    context = { 
        "data": data, 
        "list": number_list} 

    return render(request, "loop.html", context) 

urls.py: Here we are defining all the URL path for the different views.

from django.urls import path 

# importing views from views..py 
from mini import views 

urlpatterns = [ 
    path('simple',views.simple_view), 
    path('condition', views.check_age), 
    path('loop', views.loop), 
] 

geeks.html: Here we are printing the data which Is being passed by view function.

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> 
    <title>Homepage</title> 
</head> 
<body> 
    <h1>Welcome to Geeksforgeeks.</h1> 
<p> {{ data }}</p> 

    <ul> 
</body> 
</html> 

check_age.html: Here first we are accepting age from the user and then checking it with the jinja if it is greater than certain age or not.

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Age Checker</title> 
</head> 
<body> 
    <h1>Welcome to the Age Checker</h1> 

    <form method="post"> 
        {% csrf_token %} 
        <label for="age">Enter your age:</label> 
        <input type="number" id="age" name="age"> 
        <button type="submit">Check Age</button> 
    </form> 

    {% if age %} 
        <p>Your age is: {{ age }}</p> 
        {% if age >= 20 %} 
            <p>You are an adult.</p> 
        {% else %} 
            <p>You are not an adult.</p> 
        {% endif %} 
    {% endif %} 
</body> 
</html> 

loop.html: Here we are printing the even numbers of the list with the help of loop and condition in Jinja.

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Even Numbers</title> 
</head> 
<body> 
    <h1>{{ data }}</h1> 
    Even Numbers 
    <ul> 
        {% for number in list %} 
            {% if number|divisibleby:2 %} 
                <li>{{ number }}</li> 
            {% endif %} 
        {% endfor %} 
    </ul> 
</body> 
</html> 

The Django template language

This is one of the most important facilities provided by Django Templates. A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. As we used for the loop in the above example, we used it as a tag. similarly, we can use various other conditions such as if, else, if-else, empty, etc. The main characteristics of Django Template language are Variables, Tags, Filters, and Comments.

Jinja Variables

Variables output a value from the context, which is a dict-like object mapping keys to values. The context object we sent from the view can be accessed in the template using variables of Django Template.

Syntax: {{ variable_name }}

Example: Variables are surrounded by {{ and }} like this:

My first name is {{ first_name }}. My last name is {{ last_name }}.

With a context of {‘first_name’: ‘Naveen’, ‘last_name’: ‘Arora’}, this template renders to:

My first name is Naveen. My last name is Arora.

To know more about Django Template Variables visit – variables – Django Templates

Jinja Tags 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, or even enable access to other template tags.

Syntax: {% tag_name %}

Example: Tags are surrounded by {% and %} like this:

{% csrf_token %}

Most tags accept arguments, for example :

{% cycle 'odd' 'even' %}

Commonly used Tags

Tag Description
Comment Used to add comments within Django template files.
cycle Cycles among several strings in a sequence.
extends Indicates that a template extends another template.
if Conditional tag to control the flow of template rendering based on conditions.
for loop Iterates over each item in a sequence.
for ... empty loop Executes a block of code if a loop is empty.
Boolean Operators Used for logical operations in templates.
firstof Outputs the first variable passed that is not empty.
include Includes the contents of another template.
lorem Generates lorem ipsum placeholder text.
now Displays the current date and time.
url Constructs a URL based on the provided view name and optional parameters.

Filters Django Template Engine provides filters that are used to transform the values of variables and tag arguments. We have already discussed major Django Template Tags. Tags can’t modify the value of a variable whereas filters can be used for incrementing the value of a variable or modifying it to one’s own need.

Syntax: {{ variable_name | filter_name }}

Filters can be “chained.” The output of one filter is applied to the next. {{ text|escape|linebreaks }} is a common idiom for escaping text contents, then converting line breaks to

tags.

Example: {{ value | length }}

If value is [‘a’, ‘b’, ‘c’, ‘d’], the output will be 4.

Major Template Filters

Filter Description
add Adds the value on the right to the value on the left.
addslashes Escapes characters that are used in HTML.
capfirst Capitalizes the first character of a string.
center Centers the value in a field of a given width.
cut Removes all values of a specified string.
date Formats a date according to the given format.
default Returns the value of the variable, or a default value if the variable is not set or is None.
dictsort Sorts a list of dictionaries by a given key.
divisibleby Checks if the value is divisible by the argument.
escape Marks a string as safe for HTML output.
filesizeformat Formats the value as a human-readable file size.
first Returns the first item in a list.
join Joins the elements of a list with a specified string.
last Returns the last item in a list.
length Returns the length of the value.
line numbers Adds line numbers to a block of text.
lower Converts a string to lowercase.
make_list Converts a string to a list.
random Returns a random item from a list.
slice Returns a slice of a list.
slugify Converts a string to a slug.
time Formats a time according to the given format.
timesince Returns the time since a given date.
title Converts the first character of each word to uppercase.
unordered_list Formats a list as an unordered HTML list.
upper Converts a string to uppercase.
wordcount Counts the number of words in a string.

Comments Template ignores everything between {% comment %} and {% end comment %}. An optional note may be inserted in the first tag. For example, this is useful when commenting out code for documenting why the code was disabled.

Syntax: {% comment 'comment_name' %}
{% endcomment %}

Example:

{% comment "Optional note" %}
    Commented out text with {{ create_date|date:"c" }}
{% endcomment %}

To know more about using comments in Templates, visit comment – Django template tags

Template Inheritance

The most powerful and thus 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. extends tag is used for the inheritance of templates in Django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables.

Syntax: {% extends 'template_name.html' %}

Example: Assume the following directory structure:

dir1/
    template.html
    base2.html
    my/
        base3.html
base1.html

In template.html, the following paths would be valid:


{% extends "./base2.html" %} 
{% extends "../base1.html" %} 
{% extends "./my/base3.html" %}