Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent TWIG from removing a space before a variable

Tags:

twig

I have this use case.

Default text, in a span, to be used throughout page. Use jQuery to change text from "placeholder" to "specific case"

Ie,

Inside html i want to do this: (twig / html & js)

{% block content %}
{% set location = '<span id="location">Somewhere</span>' %}

<p>Hey, hows the weather in {{ location | raw }}?</p>


<script>
    var location = detectLocation();
    update $(#location).html('location');
<script>

Desired output pre script running:

Hey, hows the weather in Somewhere?

Desired output post script running (assumes it outputs Austrailia):

Hey, hows the weather in Australia?

..But what I get thanks to twig stripping spaces:

Hey, hows the weather inSomewhere?

like image 498
Nick Avatar asked Feb 08 '17 21:02

Nick


1 Answers

This happened to me after moving from php7.0 to php7.4.3 on a legacy codebase that was still using twig 1.*.

If you can't update twig to a newer version, here's the fix.

edit twig/twig/lib/Twig/Lexer.php, on line 163 change:

if (isset($this->positions[2][$this->position][0]) ) {
    $text = rtrim($text);
}

to

if (isset($this->positions[2][$this->position][0]) && ($this->options['whitespace_trim'] === $this->positions[2][$this->position][0])) {
   $text = rtrim($text);
}

Even better fix: update your version of twig.

like image 105
scp Avatar answered Oct 20 '22 21:10

scp