Skip to content
Myr

Reword context processors for functions.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Ron DuPlain · committed by Ron DuPlain · parent d33f999 · Browse files · 1 file+14 added−12 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+14 added−12 removed

  • other:+14 added−12 removed

1 file+14 added−12 removed

modified:docs/templating.rst+14 added-12 removed
145 unmodified lines
146147Whenever you do this, please be very cautious about the variables you are148using in this block.149150.. _registering-filters:151152Registering Filters153-------------------154155If you want to register your own filters in Jinja2 you have two ways to do
21 unmodified lines
177context processors exist in Flask. Context processors run before the178template is rendered and have the ability to inject new values into the179template context. A context processor is a function that returns a180dictionary. The keys and values of this dictionary are then merged with179the template context::181the template context, for all templates in the app::182183 @app.context_processor184 def inject_user():185 return dict(user=g.user)
2 unmodified lines
188the template with the value of `g.user`. This example is not very189interesting because `g` is available in templates anyways, but it gives an190idea how this works.191190It is also possible to inject functions that can have any number of191arguments::192Variables are not limited to values; a context processor can also make193functions available to templates (since Python allows passing around194functions)::195196 @app.context_processor194 def price_formatter():195 def loader(amount, currency=u'€'):197 def utility_processor():198 def format_price(amount, currency=u'€'):199 return u'{0:.2f}{1}.format(amount, currency)197 return dict(format_price=loader)200 return dict(format_price=format_price)201199The above construct registers a "variable" function called200`format_price` which can then be used in template::202The context processor above makes the `format_price` function available to all203templates::204205 {{ format_price(0.33) }}206204The difference from regular context processor' variables is that functions205are evaluated upon template rendering compared to variables whose values206are created during `app` startup . Therefore "variable" functions make it207possible to inject dynamic data into templates.207You could also build `format_price` as a template filter (see208:ref:`registering-filters`), but this demonstrates how to pass functions in a209context processor.