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 paassing 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,

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Create a template in templates/geeks.html,

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Software Developer at GeeksForGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.