tags:

views:

58

answers:

2

I'am new to the Jinja2 template engine. Is there something like the view-helpers from Zend Framework? Can i create simple functions and reuse them all over all my template-files?

Something like this?

#somewhere in my python code:
def nice_demo_function(message):
    """"return a simple message"""
    return message

So i can to use that:

<!-- now in my template-file -->
{%  nice_demo_function('yes, this works great!') %}
+3  A: 

There are a number of ways you can expose helper functions to your templates. You could define them using macros, and then import them into templates that use them. You could add functions to the globals attribute of your Template objects, or pass them to the render() method. You could subclass Template to do the same without having to repeat yourself each time. If you want to get really fancy, you could look into writing extensions as well (but you probably don't need to go that deep).

Forest
The global thing was excactly what i needed...
DerKlops
+1  A: 

At some point you will have created a Jinja2 environment. The environment has an attribute on it called filters which is a dict that maps names to functions. So what you want to do is:

def my_helper(value):
  return "-~*#--- %s ---#*~-" % value

env = Jinja2.Environment(...)
env.filters['my_helper'] = my_helper

Now in your template you can do:

<p>The winner is {{ winner | my_helper }}</p>

And your function will be called with the value of the variable, in this case winner. If you are using Pylons, this all happens in config/environment.py.

Jesse Dhillon