我正在尝试为Twig制作的星级评分系统添加“ semi”类。 我无法创建自定义函数,因此需要在“前端”完成。
我尝试过的是这个
{% for i in range(0, 5, 0.5) | limit(5) %} {# limit to 5 stars #}
{% set starClass = (productScore >= i ? "on" : "off") %}
<span class="star fa fa-star {{ starClass }}"></span>
{% endfor %}
当productScore
等于3时,我得到如下结果:
<span class="star fa fa-star on"></span>
<span class="star fa fa-star on"></span>
<span class="star fa fa-star on"></span>
<span class="star fa fa-star off"></span>
<span class="star fa fa-star off"></span>
但是当semi
等于3.5时,如何创建一个同时添加类名productScore
的函数呢?
<span class="star fa fa-star on"></span>
<span class="star fa fa-star on"></span>
<span class="star fa fa-star on"></span>
<span class="star fa fa-star semi"></span>
<span class="star fa fa-star off"></span>
有人有主意吗?
答案 0 :(得分:1)
我会喜欢这样的东西
{% set productScore = 3.5 %}
{% for i in range(0, 4) %}
{% set starClass = productScore - i >= 1 ? 'on' : (productScore - i >= 0.5 ? 'semi' : 'off') %}
<span class="star fa fa-star {{ starClass }}"></span>
{% endfor %}