防止 TWIG 删除变量前的空格

Nic*_*ick 8 twig

我有这个用例。

跨页中的默认文本,用于整个页面。使用 jQuery 将文本从“占位符”更改为“特定情况”

IE,

在 html 中我想这样做:(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>
Run Code Online (Sandbox Code Playgroud)

运行所需的输出预脚本:

嘿,某处的天气怎么样?

运行所需的输出后脚本(假设它输出澳大利亚):

嘿,澳大利亚的天气怎么样?

..但是由于树枝剥离空间,我得到了什么:

嘿,某处的天气怎么样?

scp*_*scp 10

在仍然使用 twig 1.* 的遗留代码库上从 php7.0 移动到 php7.4.3 后,这发生在我身上。

如果您无法将 twig 更新到较新版本,这里是修复程序。

编辑twig/twig/lib/Twig/Lexer.php,第 163 行更改:

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

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

更好的解决方法:更新您的树枝版本。

  • 将我的服务器移至新服务器后,我花了几周时间才找到这个答案,并意识到这是旧 Twig 1.16.3 与 PHP 7 的冲突。我们将 Twig 移至 Composer,更新了 Twig 版本,现在这个问题消失了。 (2认同)