Flask上下文处理器功能 [英] Flask context processors functions

查看:50
本文介绍了Flask上下文处理器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Following the minimal example on the Flask pages I'm trying to build a context processor:

context_procesor.py

context_procesor.py

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

app.py(在应用工厂中)

app.py(within an app factory)

from context_processor import inflect_this

app.context_processor(inflect_this)

使用以前的基于数字的单词变形功能,很简单,我已经将其作为一个jinja过滤器,但想知道是否可以将其用作上下文处理器.

Using a previous inflection function that inflects a word based on number, simple I already have it as a jinja filter but wanted to see if I could do it as a context processor.

在以下页面的底部给出示例: http://flask.pocoo.org/docs/templating/,这应该可以,但不能.我得到:

Given the example at the bootom of the page here: http://flask.pocoo.org/docs/templating/, this should work but does not. I get:

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

我对您的了解还不够,无法了解发生了什么.谁能告诉我这是怎么回事?

I do not understand enough you to see what is going on. Can anyone tell me what is wrong?

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

可以添加功能,并且似乎比将方法包装到方法中要少,在方法中,app.context_processor可能仍会中继到jinja_env.globals.

works to add functions and seems to be less overhead than wrapping a method in a method, where app.context_processor probably relays to jinja_env.globals anyway.

推荐答案

我不确定这是否能完全回答您的问题,因为我还没有使用过应用程序工厂.

I'm not sure if this entirely answers your question, as I haven't used app factories.

但是,我从一个蓝图上尝试过,这对我有用.您只需要在装饰器中使用蓝图对象,而不是默认的"app"即可:

However, I tried this from a blueprint, and this works for me. You just have to use the blueprint object in the decorator instead of the default "app":

thingy/view.py

thingy/view.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)

templates/thingy_test.html

templates/thingy_test.html

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

我在模板中看到了预期的"$ 0.33".

and I see the expected "$0.33" in the template.

希望有帮助!

这篇关于Flask上下文处理器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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