if..else 自定义模板标签 [英] if..else custom template tag

查看:20
本文介绍了if..else 自定义模板标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的 Django 项目中实现一个自定义权限应用程序,但我不知道如何实现一个自定义模板标记来检查特定对象实例的登录用户的权限并显示一段基于检查结果.

I'm implementing a custom permissions application in my Django project, and I'm lost as to how to implement a custom template tag that checks a logged in user's permissions for a specific object instance and shows a piece of HTML based on the outcome of the check.

我现在拥有的是(伪代码):

What I have now is (pseudocode):

{% check_permission request.user "can_edit" on article %}
    <form>...</form>
{% endcheck %}

('check_permission' 是我的自定义模板标签).

('check_permission' is my custom template tag).

模板标签接受用户、权限和对象实例,并返回封闭的 HTML(表单).这目前工作正常.

The templatetag takes in the user, the permission and the object instance and returns the enclosed HTML (the form). This currently works fine.

然而,我想做的是:

{% if check_permission request.user "can_edit" on article %}
    <form>...</form>
{% else %}
    {{ article }}
{% endif %}

我已经阅读了分配标签,但是我担心我会用这个污染上下文变量空间(这意味着我可能会覆盖以前的权限上下文变量).换句话说,由于上下文变量是在不同级别定义的(在我的例子中是视图、中间件,现在是这个赋值模板标签),我担心可维护性.

I've read about the assignment tag, but my fear is that I would pollute the context variable space with this (meaning I might overwrite previous permission context variables). In other words, as the context variables are being defined on different levels (the view, middleware in my case, and now this assignment template tag), I'm worried about maintainability.

推荐答案

您可以在 if 语句中使用模板过滤器.因此,您可以将标签重写为过滤器:

You can use template filters inside if statements. So you could rewrite your tag as a filter:

{% if request.user|check_can_edit:article %}

请注意,将多个不同类型的参数传递给过滤器是很棘手的,因此您可能希望每个权限使用一个过滤器,上面我使用了 check_can_edit.

Note that it's tricky to pass multiple arguments of different types to a filter, so you'll probably want to use one filter per permission, above I've used check_can_edit.

这篇关于if..else 自定义模板标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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