Smarty - Whitespace Control
Every now an then the need for fine-grained whitespace control pops up in the smarty forums. While Smarty itself doesn't offer whitespace control functionality, we can easily implement it ourselves.
We are talking about how whitespace around template tags like {foreach $foo as $bar} … {/foreach}
are to be handled. Should there be newlines before and after block-level tags? Should they be stripped completely? Any way you go about this, there'll be a couple of developers complaining. So whatever decision you make as a library developer, it will be the wrong one.
The authors of Jinja, a template engine written in python, acknowledged this fact and came up with a simple solution called whitespace control. They would interpret {-foreach-}
to remove whitespace before and after the tag. With this approach any developer could fine tune the spaces around their tags.
While Smarty's parser does not implement something similar, it does provide a plugin API that allows us to. I've implemented (and enhanced) the Jinja whitespace control approach for Smarty: Smarty - Whitespace Control Plugin.
Whitespace Control Options
- {-tag}
- remove white space infront of tag up to the previous non-whitespace character or beginning of the line
- {--tag}
- remove white space infront of tag up to the previous non-whitespace character
- {+-tag}, {-+tag}
- replace white space infront of tag up to the previous non-whitespace character by a single line-break
- {tag-}
- remove white space after tag up to the next non-whitespace character or end of the line
- {tag--}
- remove white space after tag up to the next non-whitespace character
- {tag+-}, {tag-+}
- replace white space after tag up to the next non-whitespace character by a single line-break
- {tag+}
- replace white space after tag up to the end of the line with an additional line-break
Loading the Filter
Save the file prefilter.whitespace_control.php to your plugin directory and have it loaded with
et voila, you're in full control of your whitespace!
The author does not allow comments to this entry
Comments
Display comments as Linear | Threaded