如何使用jinja2复制模板中的名称?

cra*_*ice 15 python templates jinja2 pluralize

如果我有一个名为num_countries的模板变量,要使用Django复数,我可以写下这样的东西:

countr{{ num_countries|pluralize:"y,ies" }}
Run Code Online (Sandbox Code Playgroud)

有没有办法用jinja2做这样的事情?(我知道这在jinja2中不起作用)jinja2的替代方案是什么?

谢谢你的提示!

Fil*_*ina 27

盖伊阿迪尼的回答肯定是要走的路,虽然我认为(或者我可能误用它)它与Django中的复数过滤器并不完全相同.

因此这是我的实现(使用装饰器注册)

@app.template_filter('pluralize')
def pluralize(number, singular = '', plural = 's'):
    if number == 1:
        return singular
    else:
        return plural
Run Code Online (Sandbox Code Playgroud)

这样,它的使用方式完全相同(好吧,参数以稍微不同的方式传递):

countr{{ num_countries|pluralize:("y","ies") }}
Run Code Online (Sandbox Code Playgroud)


Thi*_*ter 15

目前的Jinja版本具有i18n扩展,增加了不错的翻译和复数标签:

{% trans count=list|length %}
There is {{ count }} {{ name }} object.
{% pluralize %}
There are {{ count }} {{ name }} objects.
{% endtrans %}
Run Code Online (Sandbox Code Playgroud)

你可以使用它,即使你实际上没有多种语言版本 - 如果你曾经添加其他语言,你将有一个不错的基础,不需要改变(不是所有语言复数通过添加's',有些甚至有多个复数形式).


Guy*_*ini 5

根据 Jinja 的文档,没有内置过滤器可以满足您的需求。您可以轻松设计自定义过滤器来执行此操作,但是:

def my_plural(str, end_ptr = None, rep_ptr = ""):
    if end_ptr and str.endswith(end_ptr):
        return str[:-1*len(end_ptr)]+rep_ptr
    else:
        return str+'s'
Run Code Online (Sandbox Code Playgroud)

然后在您的环境中注册它:

environment.filters['myplural'] = my_plural
Run Code Online (Sandbox Code Playgroud)

您现在可以使用 my_plural 作为 Jinja 模板。