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条)

报告相同问题?

悬赏问题

  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥15 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver