Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 825
user3287829 Avatar asked Dec 02 '22 20:12

user3287829


2 Answers

Did you register the filter?

environment.filters['my_multiplier'] = my_multiplier

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

Hope this helps!

like image 78
Andrew Kloos Avatar answered Dec 05 '22 08:12

Andrew Kloos


Adding some info because I found this while googling a similar issue.

Current answer from https://flask.palletsprojects.com/en/2.0.x/templating/#registering-filters:

Registering Filters

If you want to register your own filters in Jinja2 you have two ways to do that. You can either put them by hand into the jinja_env of the application or use the template_filter() decorator.

The two following examples work the same and both reverse an object:

@app.template_filter('reverse')
def reverse_filter(s):
    return s[::-1]

def reverse_filter(s):
    return s[::-1]
app.jinja_env.filters['reverse'] = reverse_filter

In case of the decorator the argument is optional if you want to use the function name as name of the filter. Once registered, you can use the filter in your templates in the same way as Jinja2’s builtin filters, for example if you have a Python list in the app context called mylist:

{% for x in mylist | reverse %}{% endfor %}

For the above example that would mean that llamawithabowlcut is correct and the OP's code should work as shown.

I have tried to rebuild the described use-case, but I am not sure where the OP got the Template class from - the complete code would have been more helpful here.

like image 36
ootwch Avatar answered Dec 05 '22 10:12

ootwch