在django模板中执行getattr()样式查找 [英] Performing a getattr() style lookup in a django template

查看:278
本文介绍了在django模板中执行getattr()样式查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您不提前知道某个属性的名称时,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屋!

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