dounei9043 2015-11-25 16:20
浏览 146
已采纳

我们可以在编译时使用twig删除空格,而不是在渲染时删除它吗?

Twig has the {% spaceless %} tag, which removes all the white space between HTML tags.

However, it does this with a preg_replace when you render the template. Fine on small files, but if you have a large complex template there's a performance hit.

I feel like it should be possible to strip the whitespace out at compile time?

My compiled template is full of stuff like

        echo "    <h2>Heading</h2>
";

Where the template has included the following:

<section>
    <h2>Heading</h2>
</section>

What I want on the final rendered HTML is

<section><h2>Heading</h2></section>

Why couldn't twig (very simply) add a trim in when building the compiled template, to give us:

echo "<h2>Heading</h2>";

in the compiled template php code.

I get that there could still be whitespace in whatever data I populate the template with inside {{ }}, but I can control that from my PHP easily.

  • 写回答

3条回答 默认 最新

  • dongzhenshen7435 2015-11-25 17:03
    关注

    OK, after much digging in the library trying to work out which files generate which bits of the output, I've finally found this "fix".

    Change

    ->string($this->getAttribute('data'))
    

    to

    ->string(trim(preg_replace('/>\s+</', '><', $this->getAttribute('data'))))
    

    On line 30 of /lib/Twig/Node/Text.php.

    Doing that correctly gives me a "spaceless" output, but without requiring the expensive template-render-time preg_replace call.

    Will it cause problems? Possibly in some use cases, maybe with a partial <pre> or <textarea> tag. I can't see either of those being an issue for me though.

    Any gotchas that I've not thought of?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失