Remove extra HTML spaces in Smarty

假如想象 提交于 2019-12-05 03:46:34

问题


We heavily use Smarty for all our front end templating. I have observed the following situation:

When my Smarty template is similar to as follows:

<li>
    {if $a == 'A'}
        {$var1}
    {else}
        {$var2}
    {/if}
    <br><span>SUBTEXT</span>
</li>

The final HTML which is delivered to the browser is:

<li>
                            65
                        <br><span>SUBTEXT</span>
        </li>

I would expect it to be more clean and something like:

<li>
    65<br><span>SUBTEXT</span>
</li>

or better:

<li>65<br><span>SUBTEXT</span></li>

Anyway I can do this with some configuration settings in Smarty 3? Any setting to format and clean the final HTML created?

Thanks


回答1:


You can load the output filter trimwhitespace. It removes HTML comments (except ConditionalComments) and reduces multiple whitespace to a single space everywhere but <script>, <pre>, <textarea>.

You can easily make the filter remove space between <two> <tags> by altering line 62. change

'#(:SMARTY@!@|>)\s+(?=@!@SMARTY:|<)#s' => '\1 \2',

to

'#(:SMARTY@!@|>)\s+(?=@!@SMARTY:|<)#s' => '\1\2',

and you're done.

Output filters run AFTER the template is rendered and BEFORE it's sent to the browser. {strip} runs before the template is processed - it's a compile-time thing. So the following

{$some_var = "Hello\nworld"}
{strip}
  -
  {$}
  -
{/strip}

will output

-hello
world-

while the outputfilter would return

- hello world -



回答2:


You can use {strip} to remove all white space and carriage returns in part of a template:

http://www.smarty.net/docsv2/en/language.function.strip.tpl

{strip}
<li>
    {if $a == 'A'}
        {$var1}
    {else}
        {$var2}
    {/if}
    <br><span>SUBTEXT</span>
</li>
{/strip}

Output should be:

<li>65<br><span>SUBTEXT</span></li>

This may be inconvenient, but be aware that white space and newlines have a significant impact/importance on the HTML output, and stripping them globally can have unintended side effects.




回答3:


If you want to remove the whitespace from all files simple call:

$oSmarty->loadFilter("output", "trimwhitespace");
$oSmarty->display($display);

Further info have a look at PHP class: smarty_outputfilter_trimwhitespace and docs: http://www.smarty.net/docs/en/advanced.features.outputfilters.tpl



来源:https://stackoverflow.com/questions/9207163/remove-extra-html-spaces-in-smarty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!