Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove extra HTML spaces in Smarty

Tags:

smarty

smarty3

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

like image 826
Sparsh Gupta Avatar asked Feb 15 '26 13:02

Sparsh Gupta


2 Answers

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.

like image 52
Wesley Murch Avatar answered Feb 21 '26 14:02

Wesley Murch


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 -
like image 28
rodneyrehm Avatar answered Feb 21 '26 16:02

rodneyrehm