Open In App

variables – Django Templates

Last Updated : 02 Dec, 2021
Like Article

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. 


{{ variable_name }}

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 geeksforgeeks having an app named geeks. 

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 geeks/, 


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

Create a url path to map to this view. In geeks/, 


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

Create a template in templates/geeks.html, 


My First Name is {{ first_name }}.
My Last Name is  {{ last_name }}.

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads