Django模板 - 动态变量名
下午好,
如何在Django模板中使用变量名?
How can I use a variable variable name in Django templates?
我有使用上下文
, has_perm
的自定义身份验证系统进行检查,以查看用户是否可以访问指定的部分。
I have a custom auth system using context
, has_perm
checks to see if the user has access to the specified section.
deptauth
是一个带有限制组名称的变量,即SectionAdmin。我认为 has.perm
实际上是检查'deptauth'
而不是变量值 SectionAdmin
deptauth
is a variable with a restriction group name i.e SectionAdmin. I think has.perm
is actually checking for 'deptauth'
instead of the variable value SectionAdmin
as I would like.
{%if has_perm.deptauth %}
我该怎么做? has_perm。{{depauth}}
或沿着这些行的东西
How can I do that? has_perm.{{depauth}}
or something along those lines?
编辑 - 更新代码
{% with arg_value="authval" %}
{% lookup has_perm "admintest" %}
{% endwith %}
{%if has_perm.authval %}
window.location = './portal/tickets/admin/add/{{dept}}/'+val;
{% else %}
window.location = './portal/tickets/add/{{dept}}/'+val;
{%endif%}
has_perm不是一个对象..它在我的上下文处理器(permchecker):
has_perm isn't an object.. it's in my context processor (permchecker):
class permchecker(object):
def __init__(self, request):
self.request = request
pass
def __getitem__(self, perm_name):
return check_perm(self.request, perm_name)
你最好写自己的自定义模板标签。这样做并不难,而且对于这种情况也是正常的。
You're best off writing your own custom template tag for that. It's not difficult to do, and normal for this kind of situation.
我还没有测试过这个,但这些方面的东西应该可以工作。记住正确处理错误!
I have not tested this, but something along these lines should work. Remember to handle errors properly!
def lookup(object, property):
return getattr(object, property)()
register.simple_tag(lookup)
如果你试图获取属性而不是执行一个方法,删除那些()
。
If you're trying to get a property rather than execute a method, remove those ()
.
并使用它:
{% lookup has_perm "depauth" %}
注意 has_perm
是一个变量,而depauth
是一个字符串值。这将通过字符串进行查找,即get has_perm.depauth
。
Note that has_perm
is a variable, and "depauth"
is a string value. this will pass the string for lookup, i.e. get has_perm.depauth
.
您可以使用变量调用它:
You can call it with a variable:
{% with arg_value="depauth_other_value" %}
{% lookup has_perm arg_value %}
{% endwith %}
这意味着变量的值将用于查找,即 has_perm.depauth_other_value
'。
which means that the value of the variable will be used to look it up, i.e. has_perm.depauth_other_value
'.