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

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

问题描述

我在我的Django项目中实现了一个自定义权限应用程序,而且我失去了如何实现一个自定义模板标签来检查特定对象实例的登录用户的权限,并显示一个基于检查的结果。



我现在是(伪代码):

 <$文章%} 
< form> ...< / form>上的c $ c> {%check_permission request.usercan_edit
{%endcheck%}

('check_permission'是我的自定义模板标签) / p>

模板标签接收用户,权限和对象实例,并返回附带的HTML(表单)。这个工作正常。



然而,我想要做的是:

  {%if check_permission request.usercan_edit在文章%} 
< form> ...< / form>
{%else%}
{{article}}
{%endif%}

我已阅读有关作业标签,但我的恐惧是我会用这个污染上下文变量空间(意味着我可能会覆盖以前的权限上下文变量)。换句话说,由于上下文变量被定义在不同的级别(我的情况下的视图,中间件,现在这个赋值模板标签),我担心可维护性。

解决方案

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



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

请注意,将不同类型的多个参数传递给过滤器非常棘手,因此您可能需要使用一个过滤器每个许可,上面我使用了 check_can_edit


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' is my custom template tag).

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

What I would like to do however, is something like:

{% 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.

解决方案

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

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

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..el自定义模板标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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