我们可以在编译时使用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.

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?

The right tool for your needs if the spaces are in the template source is the whitespace control feature of Twig: http://twig.sensiolabs.org/doc/templates.html#whitespace-control

If the spaces are in a variable being displayed in the output, you should use the trim filter (or trim the variable before passing it to Twig, which will do the same anyway)