templates - Python lambdas in Jinja2 -


i use jinja2 website template engine, , helper functions used in templates i've implemented macros, one. it's python code:

def arrow_class_from_deg(angle):     if angle 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 css class arrow, closest specified angle. function (and be) used in templates, makes sense implement in in templates too, namely macro. however, trying noticed jinja2 doesn't seem support python lambdas. true, , if yes how write function better (i hope loop isn't necessary here)?

register 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 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):     ''' love name entered.      usage: {{ "john" | i_love_you }} => "i love you, john!"'''      return "i love you, %s!" %name 

Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -