{capture}

{capture}可以捕获标记范围内的输出内容,存到变量中而不显示。 任何在{capture name='foo'}{/capture} 之间的内容都会被捕获到变量,变量名可以通过name属性来指定。

捕获的内容可以通过$smarty.capture.foo变量来使用,这里foo是设置的name属性。 如果没有提供name属性,默认是default,也就是 $smarty.capture.default.

{capture}可以被嵌套使用。

属性:

参数名称 类型 必选参数 默认值 说明
name string Yes n/a 捕获区域的名称
assign string No n/a 捕获内容后赋值的变量名
append string No n/a 将捕获的内容增加到数组中

可选标记:

名称 说明
nocache 关闭捕获区域的缓存

警告

当捕获{insert}输出的时候请小心。 如果开启了$caching并且 你希望通过{insert} 在缓存的页面上显示动态内容,那么你无法捕获这些内容。

Example 7.21. {capture}使用name属性


{* we don't want to print a div tag unless content is displayed *}
{capture name="banner"}
{capture "banner"} {* short-hand *}
  {include file="get_banner.html"}
{/capture}

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

   


Example 7.22. {capture} 捕获内容到变量

下面是capture函数的演示


{capture name=some_content assign=popText}
{capture some_content assign=popText} {* short-hand *}
The server is {$my_server_name|upper} at {$my_server_addr}<br>
Your ip is {$my_ip}.
{/capture}
<a href="#">{$popText}</a>

     


Example 7.23. {capture} 捕获内容到数组变量

下面例子演示了如何多次捕获内容,形成数组。


{capture append="foo"}hello{/capture}I say just {capture append="foo"}world{/capture}
{foreach $foo as $text}{$text} {/foreach}

     

输出:


I say just hello world

  


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