我有一个书签图标,我想根据 Twig 条件启用它。
首先这是禁用检查:
启用:
如您所见,我所做的就是将收藏的类注入(inject)按钮:
class="faved"
现在我们可以互相理解了,这里是我的 Twig 测试代码,它测试这本书是否被添加了书签
{% for favs in fav %}
{% if livre.idLivre == favs.idLivre.idLivre %}
<h>favorited book in the database</h>
{% endif %}
{% endfor %}
输出
如您所见,我可以捕获数据库中最喜欢的书并打印“数据库中最喜欢的书”作为测试
这是我包含 btn 代码的完整 Twig 代码:
{% for favs in fav %}
{% if livre.idLivre == favs.idLivre.idLivre %}
<h>favorited book in the database</h>
{% endif %}
{% endfor %}
<div align="center" id="{{ livre.idLivre }}">
ajouter au favoris
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css"rel="stylesheet">
<button id="heart">
<span class="glyphicon glyphicon-heart">
<span class="glyphicon glyphicon-heart">
</span>
</span>
</button>
现在我想做的任务是更改启用图标的状态,或者换句话说,如果 Twig 条件为真,则将 class="faved"
注入(inject)按钮。
最佳答案
只需将您的条件设为内联,以确定是否应将类添加到按钮上。
我在这里创建了一个变量来确定收藏夹是否存在。然后我使用内联条件在 faved==true 时将类添加到按钮。
{% set faved = false %}
{% for favs in fav %}
{% if livre.idLivre == favs.idLivre.idLivre %}
{% set faved = true %}
<h>favorited book in the database</h>
{% endif %}
{% endfor %}
<div align="center" id="{{ livre.idLivre }}">
ajouter au favoris
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css"rel="stylesheet">
<button id="heart" class="{{ (faved) ? 'faved' : '' }}">
<span class="glyphicon glyphicon-heart">
</span>
</button>
关于javascript - 如何在 Twig 内切换类(如果有条件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55581019/