I do a few webprojects with
Flask
and I love it!
While creating a template i searched for a way to call functions from within the template, and found out that i can use a @app.context_processor
decorator.
1@app.context_processor
2def my_utility_processor():
3
4 def date_now(format="%d.m.%Y %H:%M:%S"):
5 """ returns the formated datetime """
6 return datetime.datetime.now().strftime(format)
7
8 def foo():
9 """ returns bulshit """
10 return "bar bar bar"
11
12 return dict(date_now=date_now, baz=foo)
In the jinja2 template you can now simply call the functions like this:
1{% raw %}
2
3{% for n in news %}
4 Give me some {{ baz() }}!
5{% endfor %}
6
7Copyright by me 2005 - {{ date_now("%Y") }}
8
9{% endraw %}
Lets assume news contains 2 elements, the result looks like this:
1Give me some bar bar bar!
2
3Give me some bar bar bar!
4
5Copyright by me 2005 - 2013
The important part is return dict(date_now=date_now, baz=foo)
. The first word is the key, the value is a function pointer.
The key is the keyword you write in your template code {{ baz() }}
for example, foo
is the name of the function that get called.