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

后端 未结 2 1192
星月不相逢
星月不相逢 2021-02-03 22:31

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

相关标签:
2条回答
  • 2021-02-03 22:51

    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%}
    
    0 讨论(0)
  • 2021-02-03 23:01

    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

    0 讨论(0)
提交回复
热议问题