user3287829 user3287829 - 1 year ago 86
Python Question

How do I register filters for dynamically-generated jinja2 templates in Flask?

I am new to Flask. I am trying to generate my template dynamically so that I can make a request via AJAX and append rows to a table:

def my_multiplier(n):
return n*10

def index():
content = [1,2,3,4,5]
tmplate = get_template()
html = tmplate.render(content=content)
return render_template('index.jinja2',html=html)

def get_template():
html = Template(u'''\
{% for n in conent %}
<tr><td>{{ n | my_multiplier }}</td></tr>
{% endfor %}''')
return html

I get an error: TemplateAssertionError: no filter named 'my_multiplier'

What am I doing wrong? (The template renders fine if I exclude the filter)

Answer Source

Did you register the filter?

environment.filters['my_multiplier'] = my_multiplier

Hope this helps!