从jinja2调用python函数 [英] Call a python function from jinja2

查看:107
本文介绍了从jinja2调用python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jinja2,并且我想使用类似于调用宏的语法来调用python函数作为帮助程序. jinja2似乎旨在阻止我进行函数调用,并坚持要我通过将函数复制到模板中作为宏来重复我自己.

I am using jinja2, and I want to call a python function as a helper, using a similar syntax as if I were calling a macro. jinja2 seems intent on preventing me from making a function call, and insists I repeat myself by copying the function into a template as a macro.

有没有简单的方法可以做到这一点?而且,是否有任何方法可以导入整套python函数并使它们从jinja2中进行访问,而无需经历大量的rigamarole(例如编写扩展名)?

Is there any straightforward way to do this? And, is there any way to import a whole set of python functions and have them accessible from jinja2, without going through a whole lot of rigamarole (such as writing an extension)?

推荐答案

对于使用Flask的用户,请将其放入您的__init__.py:

For those using Flask, put this in your __init__.py:

def clever_function():
    return u'HELLO'

app.jinja_env.globals.update(clever_function=clever_function)

,然后在模板中使用{{ clever_function() }}

这篇关于从jinja2调用python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆