I want to add some flexibility to my layout template, but I can't find any way to do so.
I'm looking for a way to extend
my layout template with variable, i.e. to pass a variable up in the template tree, not down.
# views.py def my_view_func(request): return render(request, "child.html")
# child.html {% extends 'layout.html' with show_sidebar=True sidebar_width_class="width_4" %} <div>Templates stuff here</div>
# layout.html {% if show_sidebar %} <div class="{{ sidebar_width_class }}"> {% block sidebar %}{% endblock %} </div> {% endif %}
I have to maintain four templates with a difference in a few lines of code. For example, I have two templates that differ from each other by a sidebar width class. Am I doing something wrong?
And this is rather simple, because Django has built-in template modules that makes a transfer easy. Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file. We won't go into a database example for this one.
Another approach to declare variables in the template is by using custom template tags. Create a custom template tag files named as custom_template_tags.py . Paste the below code in it. Now inside the HTML template use this custom template tag setvar to define a new variable.
Variable names consist of any combination of alphanumeric characters and the underscore ( "_" ) but may not start with an underscore, and may not be a number.
I suspect that block
is what you are looking for in the first place.
Form your block inside the base template like this:
{% block sidebar_wrapper %} {% if sidebar %} <div class="width{{sidebar_width}}"> {% block sidebar %}{% endblock %} </div> {% endif %} {% endblock sidebar_wrapper%}
And on your child template:
{% extends 'layout.html' %} {% block sidebar_wrapper %} {% with sidebar=True sidebar_width=4 %} {{ block.super }} {% endwith%} {% endblock sidebar_wrapper%}
What you need is an include template tag. You can include a template in another template and render that with specific context.
{% include 'layout.html' with sidebar=True sidebar_width=4 %}
Check docs here: https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#include
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With