I want to build a Django template hierarchy like so:
root.html
|_ root-dashboard.html
|_ root-regular.html
root.html
shall have an if
statement:
{% if style == "dashboard" %}
{# render some elements in a certain way #}
{% else %}
{# render those elements in a different way #}
{% endif %}
And root-dashboard.html
and root-regular.html
should individually extend root.html
by setting style
:
# root-dashboard.html
{% extend 'root.html' with style='dashboard'%}
# root-regular.html
{% extend 'root.html' with style='regular'%}
(with
above is not an actual valid syntax, its just something similar I want)
And a view can use either root-dashboard.html
or root-regular.html
to show the content in one style or the other.
How do I achieve this without the view having to set the style
context?
I want to build a Django template hierarchy like so:
root.html
|_ root-dashboard.html
|_ root-regular.html
root.html
shall have an if
statement:
{% if style == "dashboard" %}
{# render some elements in a certain way #}
{% else %}
{# render those elements in a different way #}
{% endif %}
And root-dashboard.html
and root-regular.html
should individually extend root.html
by setting style
:
# root-dashboard.html
{% extend 'root.html' with style='dashboard'%}
# root-regular.html
{% extend 'root.html' with style='regular'%}
(with
above is not an actual valid syntax, its just something similar I want)
And a view can use either root-dashboard.html
or root-regular.html
to show the content in one style or the other.
How do I achieve this without the view having to set the style
context?
1 Answer
Reset to default 1Define a {% block … %}
template tag [Django-doc] instead.
In root.html
, you don't use an if
, but:
{% block render_item %}
{# render those elements in a different way #}
{% endblock %}
then in your root-dashboard.html
, you use:
# root-dashboard.html
{% extend 'root.html' %}
{% block render_item %}
{# render some elements in a certain way #}
{% endblock %}
The idea is similar to the dynamic binding concept [wiki] in object-oriented programming, and is usually better than using if
conditions: the latter is not extensible, and thus limits later modifications.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744897767a4599798.html
{% if .. %}
probably is not a good idea: just like in OO programming where you use dynamic binding over if, it is better to use a block. – willeM_ Van Onsem Commented Mar 8 at 11:05