Flask上下文处理器函数

2024-04-26 03:16:25 发布

您现在位置:Python中文网/ 问答频道 /正文

按照Flask页面上的最小示例,我正在尝试构建一个上下文处理器:

上下文处理程序.py

def inflect_this():
    def inflectorize(number, word):
        return "{} {}".format(number, inflectorizor.plural(word, number))
    return dict(inflectorize=inflectorize)

app.py(在应用程序工厂内)

from context_processor import inflect_this

app.context_processor(inflect_this)

使用之前的屈折变化函数,根据数字屈折一个词,简单的说,我已经有了它作为一个jinja过滤器,但想看看我是否可以做它作为一个上下文处理器。

以页面bootom中的示例为例:http://flask.pocoo.org/docs/templating/,这应该可以工作,但不能。我得到:

jinja2.exceptions.UndefinedError UndefinedError: 'inflectorize' is undefined

我对你的理解不够,看不清发生了什么事。有人能告诉我怎么了吗?

编辑:

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

它可以添加函数,并且似乎比在方法中包装方法的开销要小,在方法中app.context_processor可能会转发到jinja_env.globals。


Tags: 方法pyapp示例numberdefcontext页面
1条回答
网友
1楼 · 发布于 2024-04-26 03:16:25

我不确定这是否完全回答了你的问题,因为我没有使用应用程序工厂。

然而,我从蓝图中尝试过,这对我很有用。您只需在decorator中使用blueprint对象而不是默认的“app”:

thingy/视图.py

from flask import Blueprint

thingy = Blueprint("thingy", __name__, template_folder='templates')

@thingy.route("/")
def index():
  return render_template("thingy_test.html")

@thingy.context_processor
def utility_processor():
  def format_price(amount, currency=u'$'):
    return u'{1}{0:.2f}'.format(amount, currency)
  return dict(format_price=format_price)

模板/thingy_test.html

<h1> {{ format_price(0.33) }}</h1>

我在模板中看到了预期的“$0.33”。

希望能有帮助!

相关问题 更多 >