E
E
Empty User2020-01-19 18:34:19
JavaScript
Empty User, 2020-01-19 18:34:19

How to send variable to Django template?

Good day! Help plz solve the problem!!!
There is a main.html template, there is a sidebar (sidebar.html) with a list of cars, which is shown depending on the open car, and if this is the main page, then display the last three, for example, that is, I need to pass some kind of variable there. How can I send a variable to sidebar.html? Yes, it is possible, of course, to prescribe and send data in each view, but is it possible to automate this somehow? That is, I registered it in some global variable, or set the logic for the sidebar.
And is there any way to write logic for the sidebar? That is, that he had his own class. I understand that making requests inside the template is a bad practice.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
irishmann, 2019-04-11
@irishmann

Why in the header??? On the site it is written in black and white to insert before the closing tag</body>
In the header, leave only tags <link>and <style>between the tag <head></head>The rest in the footer before closing </body>
And remove </body>from the header. Something tells me he doesn't belong there.

A
Alexander, 2020-01-19
@dimash07

I see two options:
1. Work through context_processors . Create your own processor class and add it to the settings. Then it will work on any page. Inside this processor, process urls and so on.
context_processors.py

from django.core.context_processors import request
def sidebar(request):
    return {'context_auto': ...}

settings.py
TEMPLATES = [
    { ...,
        'OPTIONS': {
            'context_processors': [
                        "context_processors.sidebar",
            ],
        },
    },
]

In any template, the "context_auto" variable will now be available, you can call {{ context_auto }} or pass it.
2. Another option. Use Inclusion tags , and not {% include "sidebar.html" %}display your sidebar through it. That is, you create a function in which you write the logic and loading sidebar.html and on the page you already include the function, and not html
templatetags/inclusion_tag.py
@register.inclusion_tag('sidebar.html', takes_context=True)
def sidebar(context):
    return ...

In main.html we write
{% sidebar %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question