KubiRoazhon KubiRoazhon - 4 months ago 27
Twig Question

How to delete white spaces of a text in twig?

I'm using the twig template engine while using symfony2. I'm trying to find a way to delete the white spaces from a text.

For example,

I play
shall become
Iplay
.

I've tried:


Answer

First let's see what you tried and why that wasn't working:

  • Spaceless: is not working because "Use the spaceless tag to remove whitespace between HTML tags, not whitespace within HTML tags or whitespace in plain text" see spaceless documentation.
  • Trim: is not working because "The trim filter strips whitespace (or other characters) from the beginning and end of a string" see trim documentation.

What you need to use is the following:

{{ 'Some Text With Spaces'|replace({' ':''}) }}

This will output:

SomeTextWithSpaces

More details in the documentation.

Comments