下午好,
如何在Django模板中使用变量变量名?
我有一个使用的自定义身份验证系统context,请has_perm检查用户是否有权访问指定的部分。
deptauth是具有限制组名称(即SectionAdmin)的变量。我认为has.perm实际上是在检查'deptauth'而不是SectionAdmin如我所愿的变量值。
{%if has_perm.deptauth %}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?has_perm.{{depauth}}或类似的规定?
编辑-更新的代码
{% 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%}
Run Code Online (Sandbox Code Playgroud)
has_perm不是对象。它在我的上下文处理器(permchecker)中:
class permchecker(object):
def __init__(self, request):
self.request = request
pass
def __getitem__(self, perm_name):
return check_perm(self.request, perm_name)
Run Code Online (Sandbox Code Playgroud)
您最好编写自己的自定义模板标签 for that. It's not difficult to do, and normal for this kind of situation.
我还没有测试过这个,但是沿着这些思路的东西应该有效。请记住正确处理错误!
def lookup(object, property):
return getattr(object, property)()
register.simple_tag(lookup)
Run Code Online (Sandbox Code Playgroud)
如果您尝试获取属性而不是执行方法,请删除这些().
并使用它:
{% lookup has_perm "depauth" %}
Run Code Online (Sandbox Code Playgroud)
请注意,has_perm是一个变量,并且"depauth"是一个字符串值。这将传递字符串进行查找,即获取has_perm.depauth.
您可以使用变量来调用它:
{% with arg_value="depauth_other_value" %}
{% lookup has_perm arg_value %}
{% endwith %}
Run Code Online (Sandbox Code Playgroud)
这意味着变量的值将用于查找它,即has_perm.depauth_other_value'.
| 归档时间: |
|
| 查看次数: |
6036 次 |
| 最近记录: |