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

c++ - Function signature as a function template parameter -

algorithm - What are some ways to combine a number of (potentially incompatible) sorted sub-sets of a total set into a (partial) ordering of the total set? -

How to call a javascript function after the page loads with a chrome extension? -