2012-09-17 11 views
5

Necesito agregar un filtro muy simple a jinja2. Básicamente, toma un número y agrega un '+' si es positivo. Seguí los documentos de jinja2 sobre cómo agregar filtros personalizados, pero parece que no funciona (en GAE).Agregar un filtro personalizado a jinja2 en GAE

Python:

def str_votes(votes): 
    if votes > 0: 
     return '+' + str(votes) 
    else: 
     return str(votes) 

# jinja2 stuff 
template_dir = os.path.join(os.path.dirname(__file__), 'templates') 
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), 
           autoescape=True) 
jinja_env.globals['str_votes'] = str_votes 

HTML (por página representada):

<div>{{ 123|str_votes }}</div> 

Esto me da un error de: TemplateAssertionError: no filter named 'str_votes'

¿Cómo puedo solucionar esto? (Hubo un similar question aquí que nunca fue respondido.)

Respuesta

6

Tienes que registrar el filtro. Algo así como:

jinja_env.filters['str_votes'] = str_votes 
1

que he hecho algo similar, mediante su registro en las variables globales:

def jinja2(self): 
     j.environment.globals['humanize_time']= humanize_time 
     return j 

continuación, llamándola con los datos que queremos pasarlo en las plantillas de este modo:

{{ humanize_time(f.last_post_time) }} 
Cuestiones relacionadas