我在Django应用程序中有一些模板,对于不同的标记/模板具有相同的功能。
Foo标记转到foo_template.html,boo标记转到boo_template.html,例如:
Foo标签:
@register.inclusion_tag('foo_template.html', takes_context=True)
def foo(context, something):
sometng = something
return {'something': sometng}Boo标签:
@register.inclusion_tag('boo_template.html', takes_context=True)
def boo(context, something):
sometng = something
return {'something': sometng}我如何使我的代码DRYer?在这种情况下,是否有更好的注册标记的方法?
发布于 2013-07-30 20:41:57
请记住,装饰器只是包装函数的语法糖,它以原始的参数作为参数。因此,您可以将上下文函数不加修饰,然后定义两个包装器:
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)https://stackoverflow.com/questions/17954734
复制相似问题