金贾2中的Python lambdas

金贾2中的Python lambdas,python,templates,lambda,jinja2,Python,Templates,Lambda,Jinja2,我使用Jinja2作为网站模板引擎,模板中使用的所有助手函数我都实现为宏,但只有一个。这是它的Python代码: 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

我使用Jinja2作为网站模板引擎,模板中使用的所有助手函数我都实现为宏,但只有一个。这是它的Python代码:

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]

它返回最接近指定角度的箭头的CSS类。此函数仅在模板中使用(并且将在模板中使用),因此在模板中实现也很有意义,即作为宏。然而,尝试这样做时,我注意到Jinja2似乎不支持Python lambdas。这是真的吗?如果是,那么如何更好地编写此函数(我希望这里不需要循环)?

将其注册为筛选器:

your_jinja_env.filters['arrow_class'] = arrow_class_from_deg
在模板中:

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

那么,在模板中实现是不可能的?
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