Samuel Seidel
Samuel Seidel

Reputation: 21

Spaceless tag inside script block

I'm trying to inline this so the rendered page isn't 100,000 lines long. It seems the spaceless tag does nothing here.

Input:

{% for log in logs -%}
    {% spaceless %}
        {
            id: {{ log.id }},
            description: '{{ log.description }}'
        },
    {% endspaceless %}
{% endfor -%}

Expected Output:

{id:17186,description:'Test Log'},
{id:17187,description:'Test Log 2'},

Output:

{
    id: 17186,
    description: 'Test Log'
},
{
    id: 17187,
    description: 'Test Log 2'
},

Upvotes: 2

Views: 598

Answers (1)

Matias Kinnunen
Matias Kinnunen

Reputation: 8560

Like the documentation says, you can "use the spaceless tag to remove whitespace between HTML tags, not whitespace within HTML tags or whitespace in plain text."

You can instead control whitespace e.g. like this:

{% for log in logs -%}
    {
        {{- 'id' }}: {{ log.id }},
        {{- 'description' }}: '{{ log.description }}'
    {{- '},' }}
{%- endfor %}

The above produces this:

{id: 17186,description: 'Test Log'},{id: 17187,description: 'Test Log 2'},

The downside is that the Twig code is much uglier.

Here's an alternative using string interpolation:

{% for log in logs -%}
    {
        {{- 'id' }}: {{ log.id }},
        {{- 'description' }}: {{ "'#{log.description}'" -}}
    },
{%- endfor %}
{id: 17186,description: 'Test Log'},{id: 17187,description: 'Test Log 2'},

The Twig code looks now better, but notice that single quotes got converted to '. You may or may not want to do something about that.

You could also do like the documentation suggests and use a third-party library like Tidy.

Upvotes: 2

Related Questions