Open In App
Related Articles

variables – Django Templates

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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 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/views.py, 

Python3

# 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/urls.py, 

Python3

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

                    

Create a template in templates/geeks.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

Last Updated : 02 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads