如何使用Django的"with"模板标记保存比较结果? [英] How to save the result of a comparison using Django's 'with' template tag?

查看:48
本文介绍了如何使用Django的"with"模板标记保存比较结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Django模板中创建一个新变量,该变量将具有比较值

I would like to create new variable in django template, which will have a value of comparison

obj.site.profile.default_role == obj

不幸的是,这些代码都不起作用:

Unfortunately none of this code works:

{% with obj.site.profile.default_role==obj as default %}{% endwith %}

{% with default=obj.site.profile.default_role==obj %}{% endwith %}

正确的语法是什么?

推荐答案

with 可以只接受普通"上下文变量.

with can take just a "plain" context variable.

您可以尝试分配标签而是将您的参数传递给它.

You could try assignment-tags instead, passing your params to it.

@register.assignment_tag
def boolean_tag(default_role, obj):
    return default_role == obj

和模板中

{% boolean_tag obj.site.profile.default_role obj as my_check %}

如果在一个模板块中使用了变量(如您尝试使用 with 的情况一样),则此解决方案很好.如果您需要在多个页面块中使用变量,则最好使用 include 标记将其添加到页面上下文中

This solution is good if variable is used in one template block (like the case of yours, when you try using with). If you need variable in several page blocks, adding it to page context with include tag is better

这篇关于如何使用Django的"with"模板标记保存比较结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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