[Fixed]-Django pass variable into template

23👍

You can try something like this:

views.py

from django.template.response import TemplateResponse

def testdex(request, template_name="myapp/includes.html"):
    args = {}
    text = "hello world"
    args['mytext'] = text
    return TemplateResponse(request, template_name, args)

includes.html

{% extends "myapp/index.html" %}
{% block includes %}
{{ mytext }}
{% endblock includes %}

And make sure you have set path for templates in settings.py

14👍

When you do {% block content %}{% endblock content %} you are telling Django that you want to be able to overwrite this section. Please note the word content can be anything to reflect what you want to overwrite.

When you do {{ variable }} you are telling Django that you want to pass a Context. In this example, variable I want to pass is called Title as the key and Portfolio as the value. Context is a dictionary that you pass in views.py like this:

def portfolio_home(request):
    return render(request, 'portfolio/work.html', {'title': 'Portfolio'})

Let’s say I want to pass a context (or a variable) into my base template. In this example, I want to pass title in the title tag of the head section of my base template.

In the html file for base.html, you need to have something like this:

<!DOCTYPE html>
<html lang="en">

{% load staticfiles %}

    <head>
        <title>{{ title }}</title>
        ...........
    </head>
</html>

In the urls.py of my project and other apps that I want to pass a title into this, I should create the view like this:

def portfolio_home(request):
    return render(request, 'portfolio/work.html', {'title': 'Portfolio'})

3👍

I found out why Django can’t pass variables to HTML because;

I didn’t have my apps url activated the function/model in views

I feel so embarrasses, for such simple mistakes.

All I need to do is add this code in my apps url

urlpatterns = [
path('', views.timedex, name='timedex'), #need add this 
path('', views.index, name='index'),
]

0👍

Add {{block.super}} before {% endblock includes %}

👤M.G

Leave a comment