问题
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