How to test for use of a django template block?

有些话、适合烂在心里 提交于 2020-01-01 12:43:49

问题


I would like to do the following:

{% if appnav %}
<hr />
<div id="appnav">
    <ul class="tabs">
        {% block appnav %}{% endblock %}
    </ul>
</div>
{% endif %}

...however, testing for the present use of a block by templates further down the inheritance chain does not seem to work.

Is there some other conditional that might do this?


回答1:


The template language doesn't provide exactly what you're looking for. Child templates can call the parent block with {{ block.super }}, but parent templates can't reference child templates.

Your best bet will probably be to write a custom template tag. There are two sections in the template manual to review.

First, Parsing until another block tag. This will give you the basics of how to parse.

Second, Parsing until another block tag and saving contents. By placing a block tag inside the custom tag, you could detect content and wrap it as appropriate. This should work, because I believe the inner block tag will be parsed first. If that doesn't work, subclass the existing block template tag provided by django to implement your special magic.



来源:https://stackoverflow.com/questions/600806/how-to-test-for-use-of-a-django-template-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!