Smarty 是什么?
为什么使用它?
使用场景和工作流
语法比较
模板继承
最佳实践
速成教程
{capture} 用于将标签之间的模板输出收集到变量中,而不是显示它。{capture name='foo'} 与 {/capture} 之间的任何内容都将收集到 name 属性中指定变量里。
可以从变量 $smarty.capture.foo 中模板中使用捕获的内容,其中 “foo” 是传递给 name 属性的值。如果您未提供 name 属性,那么 “default” 将用作名称,即 $smarty.capture.default。
{capture}'s 可以嵌套。
属性
| 属性名称 | 类型 | 是否必需 | 默认 | 描述 |
|---|---|---|---|---|
| 名称 | 字符串 | 是 | n/a | 捕获块的名称 |
| assign | 字符串 | 否 | n/a | 将捕获的输出分配到的变量名 |
| append | 字符串 | 否 | n/a | 将捕获的输出附加到的数组变量的名称 |
选项标记
| 名称 | 描述 |
|---|---|
| nocache | 禁用此捕获块的缓存 |
示例 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.tpl"}
{/capture}
{if $smarty.capture.banner ne ""}
<div id="banner">{$smarty.capture.banner}</div>
{/if}
示例 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>
示例 7.23 {capture} 到模板数组变量
此示例还演示如何使用多次 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