Django 1.3使用inclusion_tag指定要在参数中使用的模板

时间:2015-04-23 16:14:40

标签: django templates tags

我目前有两个模板标签几乎相同:

@register.inclusion_tag('content.html')
def content(key, lazy=False, params=''):
    return {'key': key, 'lazy': js_bool(lazy), 'params': params}

@register.inclusion_tag('spec.html')
def spec(key, lazy=False, params=''):
    return {'key': key, 'lazy': js_bool(lazy), 'params': params}

我想将它们合并为仅使用模板进行更改,我该怎么做?

1 个答案:

答案 0 :(得分:2)

你可以这样做:

def tag(key, lazy=False, params=''):
    return {'key': key, 'lazy': js_bool(lazy), 'params': params}

register.inclusion_tag('content.html', name='content')(tag)
register.inclusion_tag('spec.html', name='spec')(tag)

Python装饰器只不过是语法助手,你可以替换

@decorator
def function():
    pass

通过

def function():
    pass
function = decorator(function)