The Python Oracle

Python lambdas in Jinja2

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Light Drops

--

Chapters
00:00 Question
01:03 Accepted answer (Score 2)
01:39 Thank you

--

Full question
https://stackoverflow.com/questions/1637...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #templates #lambda #jinja2

#avk47



ACCEPTED ANSWER

Score 2


register it as a filter:

your_jinja_env.filters['arrow_class'] = arrow_class_from_deg

and in template:

<something class="{{ angle | arrow_class }}">blah</something>

you can use decorators to manage jinja filters easily:

class Filter(object):
    def __init__(self, filter_name=None):
         self.filter_name = filter_name

    def __call__(self, function):
         my_jinja_env.filters[self.filter_name or function.__name__] = function
         return function

@Filter()
def i_love_you(name):
    ''' say I love you to the name you entered. 
    usage: {{ "John" | i_love_you }} => "I Love You, John!"'''

    return "I Love You, %s!" %name