在if条件下调用块:django模板 [英] Calling block inside an if condition: django template

查看:82
本文介绍了在if条件下调用块:django模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在django模板中的if条件中调用一个块。



我有一个基本模板。我有许多其他扩展基本模板的模板。
我已经在基本模板中定义了一个块:

  {%block test_block%}测试{%endblock%} 

然后,我想在其他模板中的某个条件下覆盖此块。如果条件失败,块不应该被覆盖。这是我写的东西:

  {%if test_value%} {%block test_block%}开发{%endblock%} {%endif%} 

实际上(或者可能是虚拟的)会忽略if条件。 >

我终于做了:

  {% block test_block%} {%if test_value%}开发{%else%} {{block.super}} {%endif%} {%endblock%} 

我不得不在这个地方做这样的事情。



这是最好的方法吗?这是唯一的办法吗?为什么我不能尝试我的第一种方式?或者我身边有任何错误吗?

解决方案

你没有犯错误 - 包含模板块,无论任何条件在他们旁边。您可以在 ExtendsNode 类的这一行中看到这一点, django / template / loader_tags.py =https://github.com/django/django/blob/master/django/template/loader_tags.py#L96 =nofollow noreferrer> Django源代码

  self.blocks = dict([(n.name,n)for n in nodelist.get_nodes_by_type(BlockNode)])

当正在呈现 {%extends%} 时,它会获取所有块节点直接从模板中存储它们,以便在父母碰到时进行渲染。不考虑孩子中的这些块是否在条件之内。


I have been trying to call a block inside an if condition in django template.

I have a base template. I have many other templates that extend the base template. I have defined a block in base template:

{% block test_block %}Test{% endblock %}

I then want to override this block on a certain condition in the other templates. If the condition fails, the block shouldn't get overridden. This is something what I have written:

{% if test_value %}{% block test_block %}Development{% endblock %}{% endif %}

This actually (or may be virtually) ignores the if condition.

What I finally did:

{% block test_block %}{% if test_value %}Development{% else %}{{ block.super }}{% endif %}{% endblock %}

I had to do something like this everywhere it was required.

Is this the best way? Is this the only way? Why can't I try the first way of mine? Or is there any mistake from my side?

解决方案

You haven't made a mistake - template blocks are included regardless of any conditionals around them. You can see this from this line of the ExtendsNode class of django/template/loader_tags.py in the Django source code:

self.blocks = dict([(n.name, n) for n in nodelist.get_nodes_by_type(BlockNode)])

When the {% extends %} is being rendered, it fetches all block nodes from the template directly and stores them for rendering when the parent comes across those blocks. Whether those blocks in the child were inside conditionals or not isn't considered.

这篇关于在if条件下调用块:django模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆