Django - Template language Intro

Django follows the MVC (Model = database-logic,  View=business-logic  Controller=presentation logic ). We can write the required logics based on programming[python] syntax in models and views but, when we want to write simple logics we should follow the django's template syntax, because programming[python]  syntax is not allowed.

We have the Template syntax as follows:

 

 
Syntax Explanation Example
{{  variable name   }} To display the variable value. Just like  " print " as in python input:
Welcome  "{{ request.user.username }}"
output:
Welcome  "Abhi Ram"
 
{% if  condition %}
     --- logic ----
{% endif  %}

It is a conditional expression same as " if " condition in python 

input:
{% if request.user.can_edit %}
    <button> Edit </button>
{% endif %}
output: 
if user has attribute "can_edit"  as True then it will give result 
 " <button> Edit </button> "
nothing otherwise.

 
{% if  condition1 %}
    --logic--
{% elif  condition2 %}
    -- logic--
{% else %}
   -- logic --
{% endif %}

 
same as python's   " if...elif....else "  just like above 
{% for  iterable object %}
   --logic--
{% endfor %}
takes an iterable object  returns an iterator object in every iteration.
To get reverse indexes use " forloop.revcounter "
input:  users = ["Naveen", "Ramu", "Danny", "Shera"]
{% for user in users %}
    {% if forloop.first %} First iter {% endif%} 
    {{ forloop.counter }} . {{ user }}
     {% if forloop.last %} Last iter {% endif%} 
{% endfor %}
output:
    
First iter
    1. Naveen
    2. Ramu
    3. Danny
    4. Shera
    Last iter
{% with  author_books = request.user|getbooks %}
      -- logic --
{% endwith %}
access the variable within the block. it's used when we require the same varialbe multiple times -
{% include 'sub_template.html'  with context=context  %}
                     or
{% include 'menu.html'  %}
This will include the partial tempate data by rendering it with the context -
{% load library %} This will load the given library and made its functionality(tags) available in the template -
{% load tag from library %} This will load a specific tag from the given library -
{% url "namespace:name" var1=1 va2=2 %} This will generate the url by taking  app namespace , view name and required data -
{% autoescape on|off %}
  {{ data }}
{% endautoescape %}

It will stop the XSS vulnerabilities  from the script.

-
{% now %} This gives current datetime and timezone Todays date: {% now "f" %}
{{ "Hello world"|lower  }} To convert the text to lowercase 

{{ "Hello world"|lower  }}  gives  "hello world"

{{ "Hello world"|upper  }} To convert the text to uppercase {{ "Hello world"|upper  }}  gives  "HELLO WORLD"
{{ "hyderabad"|capfirst  }} To convert the first letter to uppercase {{ "hyderabad"|capfirst  }} gives  "Hyderabad"
{{ "hellow world"|title }} converts the text to title case {{ "hellow world"|title }}  gives "Hello World"
{{ "hello    world "|slugify }} converts given text to slug form {{ "hello    world "|slugify }}  gives "hello-world"
{{ "this is micropyramid world"|wordcount }} counts the number of words in the text 
{{ "this is micropyramid world"|wordcount }}  gives "4"
{{  "this is micropyramid world"|truncatechars: n}} show's characters up to number "n" {{  "this is micropyramid"|truncatechars: 7}}  gives "this is ..."
{{  "this is micropyramid world"|truncatewords: n}} show's words up to number "n" {{  "this is micropyramid"|truncatechars: 2}}  gives "this is ..."
{{  query_set|length }} returns the no of objects in quesry set -
{{ query_set|slice:"start:end"  }} returns the sliced query set
{{ query_set|slice:"3:5"  }} same as  "query_set[3:5]"
{{ query_set||dictsort:"key"}} sort's the query_set based on the given key  -
{{ query_set|dictsortreversed:"key"}} sort's the query_set based on the given key  in reversed order -
{{ var_name|default:"Not assigned"}} if variable is not provided then default value is replaced -
{{ datetime_object|date:"d-m-yy"}} return the date in a given format -

Same usages as in views:     
     Operators:
   == ,  = ,  > , >= ,  < , <=,
    
Keywords:   and , or ,  not

    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Django webpacker - A compression tool to bundles css, js files Nikhila Mergu

django-webpacker is a django compressor tool which bundles css, js files to a single css, js file with webpack and updates your html files with ...

Continue Reading...
Sending emails using sendgrid on heroku for a Django App Vinisha Naladala

Integrate Sendgrid API to your Heroku app to deliver simplified emails like any notification emails, user signups etc.

Continue Reading...
How to customize Django Oscar Models, Views and URL's Chaitanya Kattineni

In order to customize models, views and urls, you need to fork an Oscar core app in which model/view resides. Then you should be able ...

Continue Reading...
open source packages

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties