Search code examples
phpsmartystrip

{strip}: how to avoid unintended whitespace removal?


{strip}
<div
     class="x"
>
{/strip}

becomes

<divclass="x">

And that is not what anyone would want.

So, the question: is there any way to avod this? Imagined approaches:

  • replace new lines by spaces, using parameters or other smarty-functions
  • add protected spaces that are not stripped/trimed

This topic on their forum doesn't have a solution, (other than - add your own custom tag). Also, please don't offer solutions in raw PHP or any other languages / frameworks.


Solution

  • You can either go with @dev's approach and capture your data and run it through the strip modifier:

    {capture name="spaces"}
    <div
         class="x"
    > ... </div>
    {/capture}
    {$smarty.capture.spaces|strip:" "}
    

    or run the captured content through a regex_replace modifier (essentially doing the same as split, but with more overhead):

    {$smarty.capture.spaces|regex_replace:"#\s+#":" "}
    

    or drop in a new custom block plugin called trimwhitespace that makes use of the outputfilter trimwhitespace:

    <?php
    function smarty_block_trimwhitespace($params, $content, Smarty_Internal_Template $template, &$repeat)
    {
      require_once SMARTY_PLUGINS_DIR . 'outputfilter.trimwhitespace.php';
      return smarty_outputfilter_trimwhitespace($content, $template->smarty);
    }
    

    call this file block.trimwhitespace.php and place it in the plugins_dir. use it in your template:

    {trimwhitespace}
    <div
         class="x"
    > ... </div>
    {/trimwhitespace}
    

    While both modifier approaches would work fine for simple HTML stuff, they'd break for content including <script> or <pre> tags. If you need those, you want to go with the wrapped outputfilter.

    If you want all your output to be run through that filter, forget altering your templates and add $smarty->loadFilter('output', 'trimwhitespace'); to your setup.