The Python Oracle

Python lambdas in Jinja2

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle4

--

Chapters
00:00 Python Lambdas In Jinja2
00:47 Accepted Answer Score 2
01:12 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