6

I am using the following block of code in a template:

<hr class="rule">

{% if entry.features | length %}
    <div class="feature-block">
        <h4 class="is-uppercase">Features</h4>
        <ul class="features fa-ul">
        {% for block in entry.features %}
            <li><i class="fa-li fa fa-check"></i> {{ block.feature }}</li>
        {% endfor %}
        </ul>
    </div>
{% endif %}

The if statement is adding whitespace to the markup which causes styling issues.

Whitespace

How can I correct this? Do I need to format the code block differently?

7

Have a look at the twig documentation regarding whitespace control:

https://twig.symfony.com/doc/2.x/templates.html#whitespace-control

In short, wrap the area where you want to remove whitespace in {% spaceless %} ... {% endspaceless %}, and use the - character inside tags to trim whitespace before and/or after.

10

You can also the hyphen/dash '-' modifier for shorter syntax and in place of the spaceless tags. Plus you get a bit more granular control where you want it, like trimming only leading or trailing space.

Example 1 taken from Twig Docs: Whitespace Control, this would remove whitespace around the if's and output of value.

{% set value = 'no spaces' %}
{#- No leading/trailing whitespace -#}
{%- if true -%}
    {{- value -}}
{%- endif -%}

{# output 'no spaces' #}

Example 2 is a possible real world scenario for retentive space people:

{%- set metaDescription = 'Page description.' -%}
{%- set metaKeywords = 'word1 word2 word3' -%}
{%- set pageTitle = 'A Title' %}

{% if metaKeywords is defined -%}
    <meta name="keywords" content="{{ metaKeywords }}" />
{%- endif %}

{% if metaDescription is defined -%}
    <meta name="description" content="{{ metaDescription }}" />
{%- endif %}

{% if pageTitle is defined -%}
    <title>{{ pageTitle }}</title>
{%- endif %}

Rendered output:

<meta name="keywords" content="word1 word2 word3" />
<meta name="description" content="Page description." />
<title>A Title</title>
  • But why? I mean this is super ugly, super annoying to type, so why isn't this a global default??? – leymannx Apr 19 '18 at 14:05
4

You have several different options, depending on what you want to do:

  • The spaceless function, which removes whitespace between HTML tags:

    {% spaceless %}
        <div>
            <strong>foo</strong>
        </div>
    {% endspaceless %}
    
    {# output will be <div><strong>foo</strong></div> #}
    
  • The trim filter, which removes whitespace from the beginning/end of a string:

    {{ block.feature | trim }}
    
1

You could always just use the Minify plugin and wrap whatever you want in:

{% minify %}

{% endminify %}

If works with inline CSS/JS, too.

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.