zicht / twig-classes
为 zicht/classes 开发的 Twig 扩展。
1.1.0
2021-12-13 08:57 UTC
Requires
- twig/twig: ^2.7 || ^3
- zicht/classes: ^2
Requires (Dev)
- phpunit/phpunit: ^4
This package is auto-updated.
Last update: 2024-09-17 16:19:51 UTC
README
为 zicht/classes 开发的 Twig 扩展。
安装
composer require zicht/twig-classes
目的
提供在 Twig 模板中轻松条件性地连接 CSS 类的功能。
使用方法
{{ classes('art-vandelay') }} ⇒ 'art-vandelay'
{{ classes(['art-vandelay', 'kramerica']) }} ⇒ 'art-vandelay kramerica'
{{ classes(['art-vandelay' => true, 'kramerica' => false]) }} ⇒ 'art-vandelay'
{{ classes('art-vandelay', ['kramerica' => false, 'kel-varnsen' => true]) }} ⇒ 'art-vandelay kel-varnsen'
示例
当通过检查一个或多个属性手动添加类时,代码可能很难阅读
{% set cx = [
image.url ? 'u-margin--b2' : 'u-margin--b0 u-text--center',
equal_height ? 'u-flex'
] %}
<article class="{{ cx|join(' ') }}">
...
</article>
使用 classes
函数后,可以更清晰地看到哪些类是由哪些属性触发的
{% set cx = classes({
'u-margin--b2': image.url,
'u-margin--b0 u-text--center': not image.url,
'u-flex': equal_height
}) %}
<article class="{{ cx }}">
...
</article>
如果您需要条件性地将类应用于多个元素,甚至可以创建一个嵌套对象。
{% set cx = {
card: classes({
'u-margin--b2': image.url,
'u-margin--b0 u-text--center': not image.url,
'u-flex': equal_height
}),
img: classes({
'u-black u-bg--red': color == 'black'
})
} %}
<article class="{{ cx.card }}">
<img class="{{ cx.img }}">
...
</article>