`

django模版中带参数调用任意函数的方法

 
阅读更多
原文地址:http://www.sharejs.com/codes/python/7616


django模版中带参数调用任意函数的方法


#template_filters.py

@register.filter
def template_args(instance, arg):
    """
    stores the arguments in a separate instance attribute
    """
    if not hasattr(instance, "_TemplateArgs"):
        setattr(instance, "_TemplateArgs", [])
    instance._TemplateArgs.append(arg)
    return instance

@register.filter
def template_method(instance, method):
    """
    retrieves the arguments if any and calls the method
    """
    method = getattr(instance, method)
    if hasattr(instance, "_TemplateArgs"):
        to_return = method(*instance._TemplateArgs)
        delattr(instance, '_TemplateArgs')
        return to_return
    return method()

# 在模版里面按照下面的方法调用
{{ instance|template_args:"value1"|template_args:"value2"|template_args:"value3"|template_method:"test_template_call" }}

# 输出结果
value1, value2, value3
#该代码片段来自于: http://www.sharejs.com/codes/python/7616
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics