{strip}:如何避免意外的空格删除


{strip}: how to avoid unintended whitespace removal?

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

<divclass="x">

这不是任何人都想要的。

所以,问题是:有没有办法避免这种情况?想象的方法:

  • 使用参数或其他智能函数用空格替换新行
  • 添加未剥离/修剪的受保护空间

这个话题在他们的论坛上没有解决方案,(除了-添加自己的自定义标签)。此外,请不要提供原始PHP或任何其他语言/框架的解决方案。

您可以使用@dev的方法并捕获数据并通过条带修饰符运行它:

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

或通过regex_replace修饰符运行捕获的内容(本质上与拆分相同,但开销更多):

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

或添加一个新的自定义块插件trimwhitespace,它使用输出过滤器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);
}

将此文件命名为block. trimwhitspace .php,并将其放在plugins_dir. php目录中。在你的模板中使用它:

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

虽然这两种修饰符方法都可以很好地处理简单的HTML内容,但它们会破坏包含<script><pre>标签的内容。如果需要这些,可以使用包装好的outputfilter。

如果你想让你所有的输出通过过滤器运行,忘记改变你的模板和添加$smarty->loadFilter('output', 'trimwhitespace');到你的设置。

保护空格:

{strip}
<div class="first{" "}
  {"second "}
  third">
{/strip}

<div class="first second third">

将代码分配给变量并尝试{$articleTitle|strip:'&nbsp;'}