Flask context processors functions


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


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


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?



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.

12/27/2012 9:36:07 PM

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":


from flask import Blueprint

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

def index():
  return render_template("thingy_test.html")

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


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

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

Hope that helps!

12/14/2012 2:46:47 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow