Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在自定义Django模板标记中处理条件块_Python_Django - Fatal编程技术网

Python 在自定义Django模板标记中处理条件块

Python 在自定义Django模板标记中处理条件块,python,django,Python,Django,我有一个自定义Django模板标记,用作条件块: {% if_has_permission request "some_permission" %} <div> <input type="text" name="sample_1"> <label><input type="checkbox" name="enable_it"> Enable</label> </div> {% endif_has_permis

我有一个自定义Django模板标记,用作条件块:

{% if_has_permission request "some_permission" %}
<div>
    <input type="text" name="sample_1">
    <label><input type="checkbox" name="enable_it"> Enable</label>
</div>
{% endif_has_permission %}
我看到的错误是:

无效的块标记:“endif”,应为“endblock”

如果有的话,我可以做什么来允许自定义标记中的条件表达式?我很确定,
{%if%}
是我唯一需要允许的情况,尽管偶尔的
{%for%}
也可能有用

以下是我的自定义模板标记代码:

@register.tag
def if_has_permission(parser, token):
    try:
        args = token.split_contents()
        tag_name, request, to_check = args[0], args[1], args[2]
        opts = None
        if(len(args) > 3):
            opts = args[3:]
    except IndexError:
        raise template.TemplateSyntaxError("Tag %r requires at least two arguments" % tag_name)

    if(not (to_check[0] == to_check[-1] and to_check[0] in ('"', "'"))):
        raise template.TemplateSyntaxError("The second argument to tag %r must be in quotes" % tag_name)

    nodelist_true = parser.parse(('endif_has_permission'),)
    parser.delete_first_token()
    return CheckPermissionNode(request, to_check[1:-1], opts, nodelist_true)

class CheckPermissionNode(template.Node):
    def __init__(self, request, to_check, opts, nodelist_true):
        self.request = template.Variable(request)
        self.to_check = to_check
        self.opts = opts
        self.nodelist_true = nodelist_true

    def render(self, context):
        rq = self.request.resolve(context)

        # Admins can always see everything
        if(rq.session['is_admin']):
            return self.nodelist_true.render(context)

        # Check to see if any of the necessary permissions are present
        hasPerm = False
        checkList = self.to_check.split('|')
        for c in checkList:
            if(c in rq.session['perms']):
                hasPerm = True
                break

        if(hasPerm):
            return self.nodelist_true.render(context)
        else:
            return ''

TemplateTag不像块-把它们想象成方法。您得到的错误是由于语法错误

要实现类似的功能,只需创建一个过滤器,它将检查一个条件(与您的标签现在所做的完全相同),并返回TrueFalse,然后像这样使用它

    {% if request|your_filter_name:"condition" %}
        <p> do_sth </p>
    {% endif %}
而不是

    your_tag request "condition"

事实证明,这确实是可能的。如果您有权限,
例程中有一个输入错误:

nodelist_true = parser.parse(('endif_has_permission'),)
应改为:

nodelist_true = parser.parse(('endif_has_permission',))
注意逗号放错了地方!
parse
函数需要一个元组。修正这个打字错误可以防止出错


顺便说一句,今天我遇到了完全相同的问题后,偶然发现了这个问题。想象一下,大约五年前,当我发现自己是最初的询问者时,我的惊讶;哈!

为什么必须将“if”条件提取到模板标记中?(我想知道)。你能不能把逻辑转移到一个常规的“如果”就行了?(有一段时间没用django了)我在想类似这样的答案你想过用标签代替标签吗?对我来说,这似乎更合适。检查这个答案,它解决了一个类似于你的问题我的知识可能已经过时,但我想知道你是否需要一个额外的“如果”在那里<代码>{%if\u拥有\u权限请求“some\u permission”%}
这可能会有帮助。。。
nodelist_true = parser.parse(('endif_has_permission'),)
nodelist_true = parser.parse(('endif_has_permission',))