user3287829 user3287829 - 6 months ago 29
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:

@app.template_filter('my_multiplier')
def my_multiplier(n):
return n*10

@app.route('/')
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

Did you register the filter?

environment.filters['my_multiplier'] = my_multiplier

http://jinja.pocoo.org/docs/api/#custom-filters

Hope this helps!

Comments