0

我在 Django 应用程序中有一些模板标签,对于不同的标签/模板具有相同的功能。

foo 标签转到 foo_template.html,boo 标签转到 boo_template.html,例如:

富标签:

@register.inclusion_tag('foo_template.html', takes_context=True)
def foo(context, something):    
    sometng = something
    return {'something': sometng}

嘘标签:

@register.inclusion_tag('boo_template.html', takes_context=True)
def boo(context, something):    
    sometng = something
    return {'something': sometng}

我怎样才能使我的代码干燥?在这种情况下是否有更好的方法来注册标签?

4

1 回答 1

0

请记住,装饰器只是将原始函数作为参数的包装函数的语法糖。因此,您可以不修饰上下文函数,然后定义两个包装器:

def common(context, something):    
    sometng = something
    return {'something': sometng}

register.inclusion_tag('foo_template.html', takes_context=True, name='foo')(common)
register.inclusion_tag('boo_template.html', takes_context=True, name='bar')(common)
于 2013-07-30T20:41:57.827 回答