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:
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:
First let's see what you tried and why that wasn't working:
What you need to use is the following:
{{ 'Some Text With Spaces'|replace({' ': ''}) }}
This will output:
SomeTextWithSpaces
More details in the documentation.
Try this:
{{ "I plays"|replace({' ':''}) }}
replace({' ':''})
.. Not sure though, I've always seen that in the syntax shown by Jayesh –
Hermelindahermeneutic You can also create your own filter to do that
Example :
class MyExtensions extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('removeWhiteSpace', array($this, 'removeWhiteSpace'), array('is_safe' => array('html'))),
);
}
public function removeWhiteSpace($string)
{
return preg_replace('/\s+/', '', $string);
}
}
Declare it as service :
myextensions.twig_extension:
class: YourProject\YourBundle\Twig\MyExtensions
public: false
tags:
- { name: twig.extension }
And call it in yours twig template :
{{ "Test remove white space"|removeWhiteSpace }}
For me this was not working when string contains non-breaking whitespaces:
stringWithNonBreakingWhitespace|replace({' ':''}
To replace non-braking whitespace you have to use escape sequence:
stringWithNonBreakingWhitespace|replace({'\xc2\xa0':''}
Use the spaceless filter to remove whitespace between HTML tags, not whitespace within HTML tags or whitespace in plain text:
{{ "<div>
<strong>foo</strong>
</div>"|spaceless }}
You can combine spaceless with the apply tag to apply the transformation on large amounts of HTML:
{% apply spaceless %}
<div>
<strong>foo</strong>
</div>
{% endapply %}
Ran into a similar need while optimizing my templates. Here's a quick way to reduce HTML whitespace in Twig:
{% if primary -%}
<div class="visually-hidden">{{ 'Primary tabs'|t }}</div>
<ul>{{ primary }}</ul>
{%- endif %}
{%- if secondary -%}
<div class="visually-hidden">{{ 'Secondary tabs'|t }}</div>
<ul>{{ secondary }}</ul>
{%- endif %}
Adding "-" inside your {%- if -%} and {%- endif -%} tags cuts out the extra spaces.
Hope this helps!
© 2022 - 2025 — McMap. All rights reserved.
{{ 'my string'|replace(' ', '') }}
and it would not work. If I replaced the replace with string to something other than nothing, it'd work. Odd. – Ramose