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 %}
{% endif %}

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


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

4 Answers 4


Have a look at the twig documentation regarding 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.


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
    Commented Apr 19, 2018 at 14:05

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

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

    {% spaceless %}
    {% 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 }}

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 and acknowledge you have read our privacy policy.

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