jinja2在模板中的单个对象中获取整个上下文

时间:2017-03-20 13:53:55

标签: jinja2

例如,我有模板 index.html custom_jinja2_filter

    <h1> My name is {{ name }} </h1>
    <h2> I'm {{ year }} years old </h2>
    <p> I'd like to pass template context to custom 
        filter like single object. Is it possible? 
        {{ ??? | custom_jinja2_filter  }} 
    </p>


def custom_jinja2_filter(context):
   name = context['name']
   year = context['year']

1 个答案:

答案 0 :(得分:2)

您可以将当前上下文传递给使用@contextfunction标记为可调用的函数:

from jinja2 import contextfunction


@contextfunction
def custom_jinja2_filter(context):
    name = context.name
    year = context.year
    return '(c) {} {}'.format(year, name)