Thursday, December 26, 2024
Google search engine
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

Recent Comments