有没有一种方法可以使Django模板中的块为可选 [英] Is there a way to make a block optional in Django template

查看:51
本文介绍了有没有一种方法可以使Django模板中的块为可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django的模板系统中,如果我想使用if语句使它成为可选的块,该怎么做?

In Django's templates system, if I have a block that I want to make optional using an if statement, how do I do it?

我正在尝试:

{% if val %}{% block title %}Archive {{ foo }}{% endblock %}{% endif %}

但这不起作用.有没有办法做到这一点,以便对于给定的值(在这种情况下为Null),不会发出该块,并且基本模板使用原始值?

But that doesn't work. Is there a way to do that, so that for a given value (in this case Null) the block isn't issued and the base template uses the original values?

让我更具体一点,以便更容易回答.

Let me be a little more specific, so that it is easier to answer.

我有一个页面,每页10个条目.然后,用户可以转到下一页并查看接下来的十个项目.对于每隔一页,它们越过第一页,我想让标题标签说"Archive 1"或"Archive 10"之类的内容,但是如果它们返回到原始页面,则不再存档,应该将其存档.只需转到基本模板中已经给出的原始网站标题即可.

I have a page with 10 entries per page. The user can then go on to the next page and see the next ten items. For each further page they go, past the first, I would like to have the title tag say something like "Archive 1" or "Archive 10" but if they get back to the original page, it is no longer archive, and it should just go to the original site title already given in the base templates.

推荐答案

据我了解, block 是在子模板中被覆盖"的占位符.必须在编译时"而不是在运行时"定义它们.

As far as I understand blocks are placeholders to be "overridden" in the child templates. They have to be defined at "compile time" and not at "run time".

对于您的特定问题,为什么不基于页码修改标题(假设您使用分页)?像这样:

As for your specific problem why not modify the title based on the page number (assuming you use pagination)? Something like this:

{% block title %}
    {% ifequal page 1 %}Current{% else %}Archive {{ page }}{% endifequal %}
{% endblock %}

这篇关于有没有一种方法可以使Django模板中的块为可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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