Monday, July 21, 2025
HomeLanguagesvariables – Django Templates

variables – Django Templates

A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variables, for loops, etc. 
This article revolves about how to use a variable in Template. A variable outputs a value from the context, which is a dict-like object mapping keys to values. 
 

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.

variables- Django templates Explanation

Illustration of How to use variables in Django templates using an Example. Consider a project named neveropen having an app named Lazyroar. 

Refer to the following articles to check how to create a project and an app in Django.  

Now create a view through which we will pass the context dictionary, 
In Lazyroar/views.py, 

Python3




# import render from django
from django.shortcuts import render
 
# create a function
def Lazyroar_view(request):
    # create a dictionary
    context = {
        "first_name" : "Naveen",
        "last_name"  : "Arora",
    }
    # return response
    return render(request, "Lazyroar.html", context)


Create a url path to map to this view. In Lazyroar/urls.py, 

Python3




from django.urls import path
 
# importing views from views..py
from .views import Lazyroar_view
 
urlpatterns = [
    path('', Lazyroar_view),
]


Create a template in templates/Lazyroar.html, 

html




My First Name is {{ first_name }}.
<br/>
My Last Name is  {{ last_name }}.


Let’s check is variables are displayed in the template. 

variables-Django-templates

RELATED ARTICLES

Most Popular

Dominic
32157 POSTS0 COMMENTS
Milvus
67 POSTS0 COMMENTS
Nango Kala
6530 POSTS0 COMMENTS
Nicole Veronica
11678 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11740 POSTS0 COMMENTS
Shaida Kate Naidoo
6625 POSTS0 COMMENTS
Ted Musemwa
6907 POSTS0 COMMENTS
Thapelo Manthata
6592 POSTS0 COMMENTS
Umr Jansen
6587 POSTS0 COMMENTS