Django pass variable into template

后端 未结 4 1839
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 15:01

Hi thank you for helping, I\'m poor in coding.

To point: I\'m doing a Django project that pass data form data-base to front-end; but right now i can\'t even pass an

相关标签:
4条回答
  • 2020-12-20 15:43

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

    0 讨论(0)
  • 2020-12-20 15:51

    You can try something like this

    views.py

    from django.template.response import TemplateResponse
    
    def testdex(requset, template_name="myapp/inculdes.html"):
        args = {}
        text = "hello world"
        args['mytext'] = text
        return TemplateResponse(request, template_name, args)
    

    inculdes.html

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

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

    0 讨论(0)
  • 2020-12-20 15:52

    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 讨论(0)
  • 2020-12-20 15:53

    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'})
    
    0 讨论(0)
提交回复
热议问题