How to Use Template Variables in Django: Simple Guide
template variables. Inside the template, you use double curly braces like {{ variable_name }} to display these variables dynamically.Syntax
Template variables in Django are placeholders for data passed from views. You use double curly braces {{ variable_name }} inside your HTML template to show the value of variable_name.
In your view, you send data as a dictionary called context. The keys in this dictionary become the variable names in the template.
{% raw %}
# views.py
from django.shortcuts import render
def my_view(request):
context = {'name': 'Alice', 'age': 30}
return render(request, 'my_template.html', context)
# my_template.html
<p>Hello, {{ name }}!</p>
<p>You are {{ age }} years old.</p>
{% endraw %}Example
This example shows how to pass variables from a Django view to a template and display them. The view sends a dictionary with keys title and items. The template uses these variables to render a heading and a list.
{% raw %}
# views.py
from django.shortcuts import render
def shopping_list(request):
context = {
'title': 'My Shopping List',
'items': ['Apples', 'Bread', 'Milk']
}
return render(request, 'shopping.html', context)
# shopping.html
<h1>{{ title }}</h1>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endraw %}Common Pitfalls
One common mistake is forgetting to pass the context dictionary from the view, so the template variables are empty or cause errors.
Another is using incorrect variable names in the template that don't match the keys in the context.
Also, trying to use Python code directly in templates instead of Django template syntax causes errors.
{% raw %}
# Wrong: missing context
from django.shortcuts import render
def wrong_view(request):
return render(request, 'template.html') # No context passed
# Right: pass context
def right_view(request):
context = {'message': 'Hello!'}
return render(request, 'template.html', context)
# Template usage
<p>{{ message }}</p>
{% endraw %}Quick Reference
- Pass data from view to template using a context dictionary.
- Use
{{ variable_name }}to display variables in templates. - Use template tags like
{% for %}to loop over lists. - Always match variable names exactly between view and template.
- Templates cannot run Python code directly; use Django template syntax.