0

Is there a way to use Twig's {% spaceless %} tag only under certain conditions?

For example, say you wanted the HTML to be spaceless in the live environment but wanted it uncompressed in the dev environment. I tried something like:

{% if isDev %}
    {% spaceless %}
{% endif %}
{# Some code... #}
{% if isDev %}
    {% endspaceless %}
{% endif %}

But this just throws a Twig error.

  • 1
    What is the Twig error that returns? Also out of curiosity, what would be the reason you would need to change the code on live/dev environments like this? – Jamie Wade Jan 19 '16 at 16:45
6

Yes, Twig (sometimes) complains if you're splitting tags which belong together into different conditionals, I ran into that issue in a similar situation.

But as already noted in the comments, I'm also curious why you want to split the spaceless tag. If it's about minifying HTML, the tag isn't very efficient anyways and I'd recommend to use something like Andrew Welch's Minify plugin instead.

|improve this answer|||||
  • It was about minifying the HTML but I wasn't aware of its lack of efficiency nor of the Minify plugin. Great tip! I will get on to that now, plus I've seen that it has a nice config that disables it for dev envioronments. – bravokiloecho Jan 20 '16 at 11:09
7

You could do it by buffering your output, i.e.

{% set output %}
{# Your code here #}
{% endset %}

{% if isDev %}
     {{ output }}
{% else %}
    {% spaceless %}
        {{ output }}
    {% endspaceless %}
{% endif %}
|improve this answer|||||
  • This is a nice solution, I wasn't aware of the {% set %}{% endset %} pair – bravokiloecho Jan 20 '16 at 11:07
  • Thx, I like that idea. I use the untouched HTML for local and dev server and the spaceless option for production. – Mario Jul 19 '16 at 9:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.