Flask context processors functions

flask, python, python-2.7

Solution

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

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

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

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

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

Hope that helps!

Problem

Following the minimal example on the Flask pages I'm trying to build a context processor: context_procesor.py ``` def inflect_this(): def inflectorize(number, word): return "{} {}".format(number, inflectorizor.plural(word, number)) return dict(inflectorize=inflectorize) ``` app.py(within an app factory) ``` from context_processor import inflect_this app.context_processor(inflect_this) ``` 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. 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? EDIT: ``` app.jinja_env.globals.update(inflectorize=inflectorize) ``` 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.

Original source