blu*_*ank 4 python flask python-2.7
按照Flask页面上的最小例子,我正在尝试构建一个上下文处理器:
context_procesor.py
def inflect_this():
def inflectorize(number, word):
return "{} {}".format(number, inflectorizor.plural(word, number))
return dict(inflectorize=inflectorize)
Run Code Online (Sandbox Code Playgroud)
app.py(在app工厂内)
from context_processor import inflect_this
app.context_processor(inflect_this)
Run Code Online (Sandbox Code Playgroud)
使用先前的变形函数,根据数字变换一个单词,简单的我已经将它作为jinja过滤器,但想看看我是否可以将它作为上下文处理器.
鉴于此处页面引导的示例:http://flask.pocoo.org/docs/templating/ ,这应该有效,但不行.我明白了:
jinja2.exceptions.UndefinedError UndefinedError: 'inflectorize' is undefined
Run Code Online (Sandbox Code Playgroud)
我不明白你看到发生了什么.谁能告诉我有什么问题?
编辑:
app.jinja_env.globals.update(inflectorize=inflectorize)
Run Code Online (Sandbox Code Playgroud)
用于添加函数,并且似乎比在方法中包装方法的开销更少,其中app.context_processor可能无论如何都会转发到jinja_env.globals.
Rac*_*ers 16
我不确定这是否完全回答了你的问题,因为我没有使用app工厂.
但是,我从蓝图中尝试了这个,这对我有用.您只需使用装饰器中的蓝图对象而不是默认的"app":
啄/ 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)
Run Code Online (Sandbox Code Playgroud)
模板/ thingy_test.html
<h1> {{ format_price(0.33) }}</h1>
Run Code Online (Sandbox Code Playgroud)
我在模板中看到预期的"0.33美元".
希望有所帮助!
归档时间: |
|
查看次数: |
14248 次 |
最近记录: |