I want to add some flexibility to my layout template but can't find any way to do that.
I'm looking for a way to extend layout template with variable, i.e. to pass 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 the difference in few lines of code now. For example, I have two templates that differ from each other by sidebar width class. Am I doing something wrong?
2 Answers
Answers 1
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/1.9/ref/templates/builtins/#include
Answers 2
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' %} {% with sidebar=True sidebar_width=4 %} {% block sidebar_wrapper %} {{ block.super }} {% endblock sidebar_wrapper%} {% endwith%}
0 comments:
Post a Comment