jinja2 中将 float 舍入为 int

mwi*_*son 1 jinja2 flask

我正在尝试在我的应用程序中创建一个评级(星星)用户界面。我的所有“评级”均为float。我想将该评级四舍五入以使其成为整数并显示那么多星星。我似乎不知道如何让 jinja 喜欢它。

评级示例:3.02.35.04.6等...

失败是因为TypeError: 'float' object cannot be interpreted as an integer

{% if book.average_score %}
  {% for s in range(book.average_score) %}
     <i class="fas fa-star"></i>
  {% endfor %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

我想我可以使用math

{% if book.average_score %}
  {% for s in range(math.ceil(book.average_score)) %}
     <i class="fas fa-star"></i>
  {% endfor %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

但是,这会导致jinja2.exceptions.UndefinedError: 'math' is undefined. 我假设这是因为我正在使用Flask并且模板不了解该math库。

然后我正在玩round

{% if book.average_score %}
  {% for s in range(round(book.average_score)) %}
     <i class="fas fa-star"></i>
  {% endfor %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

但后来我最终得到jinja2.exceptions.UndefinedError: 'round' is undefined

round我按照圆形文档做了一些更多的变化,但没有成功。我知道 Angularpipes对此类事情确实有帮助。jinja 有类似的东西吗?还是我离题太远了?

这个SOF 线程似乎是我能找到的最接近我试图解决的问题的东西。然而,似乎并没有让我走得更远。

lar*_*sks 8

您正在使用 Jinja,但您已链接到 Python 函数文档。Jinja != Python:使用 Jinja 表达式时需要使用过滤器或对象方法。因此,例如,您可以使用int过滤器:

{% if book.average_score %}
  {% for s in range(book.average_score|int) %}
     <i class="fas fa-star"></i>
  {% endfor %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

或者圆形过滤器:

{% if book.average_score %}
  {% for s in range(book.average_score|round) %}
     <i class="fas fa-star"></i>
  {% endfor %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

round您可以使用参数控制过滤器的行为method,该参数可以是common(默认)、floorceil

{% if book.average_score %}
  {% for s in range(book.average_score|round(method='ceil')) %}
     <i class="fas fa-star"></i>
  {% endfor %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

更新

看起来自从写这篇文章以来,round过滤器可能已经改变了。查看文档,该mode参数不存在,但有一个method参数。以下工作:

  • 指定精度和方法;不需要关键字参数:

    >>> t = jinja2.Template("Value: {{ value|round(2, 'ceil') }}")
    >>> print(t.render(value=4.1234))
    Value: 4.13
    
    Run Code Online (Sandbox Code Playgroud)
  • 仅指定舍入方法;使用method关键字:

    >>> t = jinja2.Template("Value: {{ value|round(method='ceil') }}")
    >>> print(t.render(value=4.1234))
    Value: 5.0
    
    Run Code Online (Sandbox Code Playgroud)

我已经更新了答案的原始部分以反映这一变化。

  • 所以这不适用于十进制类型..必须使用它 - /sf/answers/3410902421/ (3认同)