Remove extra HTML spaces in Smarty

Sparsh Gupta picture Sparsh Gupta · Feb 9, 2012 · Viewed 10.4k times · Source

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

Answer

Wesley Murch picture Wesley Murch · Feb 9, 2012

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.