Python lambdas in Jinja2

I use Jinja2 as a website template engine and all the helper functions used in the templates that I implemented as macros, but for one. This is the Python code:

def arrow_class_from_deg(angle): if angle is None: return '' arrow_directions = [ (0, 'n'), (45, 'ne'), (90, 'e'), (135, 'se'), (180, 's'), (225, 'sw'), (270, 'w'), (315, 'nw'), (360, 'n') ] return min(arrow_directions, key=lambda (ang, _): abs(ang - angle))[1] 

It returns the CSS class for the arrow that is closest to the specified corner. This function is used (and will be used) only in templates, so it makes sense to implement it in templates, namely in a macro. However, trying to do this, I noticed that Jinja2 does not seem to support Python lambdas. This is true, and if so, what is the best way to write this function (I hope the loop is not needed here)?

+4
source share
1 answer

register it as a filter:

 your_jinja_env.filters['arrow_class'] = arrow_class_from_deg 

and in the template:

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

you can use decorators to easily manage jinja filters:

 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 
+2
source

Source: https://habr.com/ru/post/1479165/


All Articles