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

标签 jinja2

例如,我有模板 index.htmlcustom_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']

最佳答案

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

from jinja2 import contextfunction


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

关于jinja2 在模板内的单个对象中获取整个上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42905444/

相关文章:

python - 使用谷歌应用程序引擎和Python,如何检查复选框是否被标记?

templates - 如何将选定的命名参数传递给 Jinja2 的包含上下文?

python - 使用 HTML 调用 python 函数

python - Jinja2 将 HTML 字符串标记为安全

html - jinja 模板内的 html 表中嵌套 For 循环

google-app-engine - Jinja2 不返回循环变量

python - 如何使用定界符在 Ansible 中拆分值

javascript - js 脚本未加载到 jinja2 模板中

python - Ansible 将字典项映射到列表

python - 在 Flask 中处理 URL 中的符号