在 Django 模板中执行 getattr() 样式查找 [英] Performing a getattr() style lookup in a django template
问题描述
当您事先不知道某个属性的名称时,Python 的 getattr() 方法很有用.
Python's getattr() method is useful when you don't know the name of a certain attribute in advance.
这个功能在模板中也会派上用场,但我从来没有想出办法来做到这一点.是否有可以执行动态属性查找的内置标签或非内置标签?
This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups?
推荐答案
我最近也不得不将此代码编写为自定义模板标签.为了处理所有查找场景,它首先进行标准属性查找,然后尝试进行字典查找,然后尝试 getitem 查找(使列表起作用),然后遵循标准未找到对象时的 Django 模板行为.
I also had to write this code as a custom template tag recently. To handle all look-up scenarios, it first does a standard attribute look-up, then tries to do a dictionary look-up, then tries a getitem lookup (for lists to work), then follows standard Django template behavior when an object is not found.
(2009-08-26 更新,现在也处理列表索引查找)
(updated 2009-08-26 to now handle list index lookups as well)
# app/templatetags/getattribute.py
import re
from django import template
from django.conf import settings
numeric_test = re.compile("^d+$")
register = template.Library()
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
return getattr(value, arg)
elif hasattr(value, 'has_key') and value.has_key(arg):
return value[arg]
elif numeric_test.match(str(arg)) and len(value) > int(arg):
return value[int(arg)]
else:
return settings.TEMPLATE_STRING_IF_INVALID
register.filter('getattribute', getattribute)
模板使用:
{% load getattribute %}
{{ object|getattribute:dynamic_string_var }}
这篇关于在 Django 模板中执行 getattr() 样式查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!