Fabien Potencier a320927535 bug #4916 Fix html_attr dropping style declarations whose value is zero (dylanpulver)
This PR was merged into the 3.x branch.

Discussion
----------

Fix html_attr dropping style declarations whose value is zero

`InlineStyle::getValue()` skips a declaration when `empty($value)` is true. That also matches `0`, `0.0` and `'0'`, which are ordinary CSS values.

```twig
{{ html_attr({style: {opacity: 0}}) }}                    {# "" #}
{{ html_attr({style: {'flex-grow': 0, color: 'red'}}) }}  {# style="color: red;" #}
{{ html_attr({style: ['opacity: 0']}) }}                  {# style="opacity: 0;" #}
{{ html_attr({class: [0, 'a']}) }}                        {# class="0 a" #}
```

Same declaration, opposite result. The numeric-key branch never consults `empty()`, and the sibling `SeparatedTokenList::getValue()` already uses an explicit `null !== $v && false !== $v` test, so token lists keep a `0`. When every declaration is dropped the attribute is omitted entirely, so `{style: {opacity: 0}}` renders nothing at all, and `HtmlExtension::htmlAttrValue('style', ['opacity' => 0])` returns `null`.

Silently affects `opacity`, `z-index`, `margin`, `padding`, `border`, `flex-grow` and custom properties.

The guard now lists the values that carry no declaration. `null`, `false`, `''` and `true` still skip, and `[]` is kept in that list so empty arrays behave exactly as before.

`html_attr.rst` documents the `null`/`false`/`true` omission rules and says nothing about zero, so no doc change is needed. `HtmlAttrTest.php` already has a case named "zero is not treated as falsy", but only for a plain attribute value.

3 tests added. Reverting the fix fails the first; a naive `null`/`false`-only guard fails the other two.

Commits
-------

c072ff85b3 Fix html_attr dropping style declarations whose value is zero
2026-09-05 11:35:27 +02:00

Twig, the flexible, fast, and secure template language for PHP
==============================================================

Twig is a template language for PHP.

Twig uses a syntax similar to the Django and Jinja template languages which
inspired the Twig runtime environment.

Sponsors
--------

.. raw:: html

    <a href="https://docs.blackfire.io/introduction?utm_source=twig&utm_medium=github_readme&utm_campaign=logo">
        <img src="https://static.blackfire.io/assets/intemporals/logo/png/blackfire-io_secondary_horizontal_transparent.png?1" width="255px" alt="Blackfire.io">
    </a>

More Information
----------------

Read the `documentation`_ for more information.

.. _documentation: https://twig.symfony.com/documentation
Languages
PHP 99.9%