如何在Flask中为动态生成的jinja2模板注册筛选器?

2024-09-26 22:54:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我对烧瓶不熟悉。我正在尝试动态生成模板,以便可以通过AJAX发出请求并将行追加到表中:

@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

我得到一个错误:TemplateAssertionError:没有名为“my_multiplier”的筛选器

我做错什么了?(如果排除筛选器,则模板呈现良好)


Tags: 模板appgetindexreturnmydefhtml
3条回答

添加一些信息,因为我在搜索类似问题时发现了这个。

来自http://flask.pocoo.org/docs/0.10/templating/的当前答案:

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 %}

对于上面的例子,这意味着llamawithabowlcut是正确的,并且OP的代码应该如图所示工作。

我试图重新构建所描述的用例,但是我不确定OP从哪里获得了Template类-完整的代码在这里会更有用。

编辑:几个月后回顾这一点,这可能更像是一次黑客攻击,而不是解决方案。不过,如果你对黑客没意见的话,也行。

对于使用2.7.2版的我来说,文档化的方法确实有效:

environment.filters['my_multiplier'] = my_multiplier  # didn't work

这可能在旧版本中有效。

相反,我通过查看代码找到了这个方法:

from jinja2 import environment
environment.DEFAULT_FILTERS['name'] = filter_function

如果有人有文档链接,请随意添加。

你登记过过滤器了吗?

environment.filters['my_multiplier'] = my_multiplier

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

希望这有帮助!

相关问题 更多 >

    热门问题