Skip to content

{capture}

{capture}用于将标签之间的模板输出收集到变量中,而不是显示它。任何在{capture name='foo'}{/capture}之间的内容都会被收集到name属性指定的变量中。

捕获的内容可以从变量$smarty.capture.foo在模板中使用,其中"foo"是传递给name属性的值。如果你没有提供name属性,那么将使用"default"作为名称,即$smarty.capture.default

{capture}可以嵌套。

属性

属性名 是否必需 描述
name 捕获块的名称
assign 要将捕获的输出分配到的变量名称
append 要将捕获的输出附加到的数组变量的名称

选项标志

名称 描述
nocache 禁用此捕获块的缓存

注意

在捕获{insert}输出时要小心。如果你启用了$caching并且你希望在缓存内容中运行{insert}命令,那么不要捕获此内容。

示例

{* 我们只有在显示内容时才打印 div 标签 *}
{capture name="banner"}
{capture "banner"} {* 简写 *}
  {include file="get_banner.tpl"}
{/capture}

{if $smarty.capture.banner ne ""}
<div id="banner">{$smarty.capture.banner}</div>
{/if}

这个例子演示了捕获函数。

{capture name=some_content assign=popText}
{capture some_content assign=popText} {* 简写 *}
服务器是 {$my_server_name|upper}{$my_server_addr}<br>
你的 ip 是 {$my_ip}.
{/capture}
<a href="#">{$popText}</a>

这个例子还演示了如何使用多次捕获调用来创建一个包含捕获内容的数组。

{capture append="foo"}hello{/capture}我只是说 {capture append="foo"}world{/capture}
{foreach $foo as $text}{$text} {/foreach}

上述例子将输出:

我只是说 hello world

另请参见 $smarty.capture{eval}, {fetch}, fetch(){assign}.