How to handle variables in template overlay

I just want to define the id attribute of the body tag in the child template. The first solution works great:

base.html:

[body{% block bodyid %}{% endblock %}]

      

child.html:

{% block bodyid %} id="myId"{% endblock %}

      

It's simple and great! But I don't like specifying id = "myId" in every child template. I just want to send the "myId" value to the parent template where it is placed in id = "....". So, I come up with this method:

base.html:

[body{% block bodyid %} id={{ bodyid }}{% endblock %}]

      

child.html:

{% block bodyid %}
    {% with 'myId' as bodyid %}
        {{ block.super }}
    {% endwith %}
{% endblock %}

      

But it is terrible and tedious to compare the first solution. Is there a good way to do this?

This problem goes deeper than bodyId management. I think I am trying to find and organize an outsole system using standard django template inheritance.

0


a source to share


2 answers


In the base template:

<body id="{% block bodyid %}{% endblock %}">

      

In child template:



{% block bodyid %}myId{% endblock %}

      

If I understand your question correctly, this should be enough to achieve what you want; just send the actual id ( myId

) to the base template.

+2


a source


You can set this through your code, if you like - so that your ID is part of your context object, and therefore does not need to be injected into the child templates, just their views.

Then you can specify a base template to get the ID from the context object, or rather just use the template syntax for it:



<body id="{{ body_id }}">

      

Individual preference here, of course, and it depends on the structure of your templates and views, but that's how I did it.

0


a source







All Articles