twigphp / Twig

Twig, the flexible, fast, and secure template language for PHP
https://twig.symfony.com/
BSD 3-Clause "New" or "Revised" License
8.17k stars 1.25k forks source link

Allow expressions in apply tag #3634

Closed Bilge closed 2 years ago

Bilge commented 2 years ago

I have come across an interesting problem where I want to conditionally apply an apply block. Consider the following example adapted from the documentation:

{% apply inky_to_html|inline_css(source('@styles/foo.css'), source('@styles/bar.css')) %}
    {# ... #}
{% endapply %}

This is fine in theory, but suppose we want to toggle between inlining and not based on the presence of a debug variable. Twig is not very well equipped to accommodate this. First, we should need to extract our CSS content to a set tag so they can be inserted at various positions without duplicating the CSS source files list.

{% set css %}
{{ source('@styles/foo.css') }}
{{ source('@styles/bar.css') }}
{% endset %}

{% apply debug ? inky_to_html : inky_to_html|inline_css(css) %}
<head>
    {% if debug %}
    <style>{{ css }}</style>
    {% endif %}
</head>
{% endapply %}

However, this is invalid since expressions are not parsed in this context.

Twig\Error\SyntaxError Unknown "debug" filter.

stof commented 2 years ago

I suggest you do that with separate {% apply %} tags in a if instead (potentially using a block to reuse the content between 2 places. Allowing expressions there is hard, because the condition is not something we can resolve at compile time to apply the filters in the AST.