Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to pass a variable to an 'extended' template in Django?

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?

like image 280
Alex T Avatar asked May 01 '16 06:05

Alex T


People also ask

How do you pass variables from Django view to a template?

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.

How do I declare a variable inside a Django template?

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.

Which characters are illegal in template variable name in Django?

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.


2 Answers

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%} 
like image 177
xpy Avatar answered Sep 17 '22 14:09

xpy


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

like image 41
Gabriel Muj Avatar answered Sep 20 '22 14:09

Gabriel Muj