我是Twig的新手并且最近开始了一个项目。在这里,我经常使用星级评分显示,这也需要一些值,例如要显示的评级或大小。
目前,我总是使用
<div class="ratingarea">
{% include 'Artist:rating.html.twig'
with {'rating': artist.rating, 'size': 'medium' } %}
</div>
到处都是,这可以完成这项工作,但我想知道,如果有选择将其减少到只接受参数并返回所需模板的函数,就像这样:
<div class="ratingarea"> {% rating(2.8, 'medium') %} </div>
这可能吗?或者另一种改进方法?
这是模板:
<span>
<div class="review-rating">
<div class="rating {{size}}-rating">
<div class="stars stars-fontawesome-o top-art">
<select class="list-rating fontawesome-o "
data-current-rating="{{rating}}">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
</div>
</div>
</span>
答案 0 :(得分:3)
你可以依靠宏,
macro.twig
{% macro rating(rating, size) %}
<span>
<div class="review-rating">
<div class="rating {{size}}-rating">
<div class="stars stars-fontawesome-o top-art">
<select class="list-rating fontawesome-o " data-current-rating="{{rating}}">
{% for i in 1..5 %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
</span>
{% endmacro %}
template.twig
{# import the macro's in the file "macro.twig" as the namespace `macro` #}
{% import "macro.twig" as macro %}
{{ macro.rating(2.5, 'medium') }}