包含
{include}
标签用于将其他模板包含在当前模板中。在当前模板中可用的任何变量在已包含的模板中也可使用。
属性
属性名称 | 必选 | 说明 |
---|---|---|
file | 是 | 要包含的模板文件名称 |
assign | 否 | 将 include 输出分配到的变量名称 |
cache_lifetime | 否 | 启用此子模板的缓存和单个缓存的生存期 |
compile_id | 否 | 使用单个 compile_id 编译此子模板 |
cache_id | 否 | 启用此子模板的缓存和单个 cache_id |
scope | 否 | 定义子模板分配的变量的范围:'parent','root' 或 'global' |
[var ...] | 否 | 局部传递给模板的变量 |
-
{include}
标签必须有包含模板资源路径的file
属性。 -
设置可选的
assign
属性将指定{include}
输出分配到的模板变量,而不是显示。类似于{assign}
。 -
变量可以作为 属性 传递给已包含的模板。明确传递给已包含的模板的任何变量只在已包含的文件范围内可用。当变量同名时,属性变量覆盖当前模板变量。
-
你可以在包含的模板中使用包含模板中的所有变量。但是在包含模板中对变量的更改或新创建的变量是局部作用域的,在
{include}
语句之后在包含模板中不可见。可以通过在{include}
语句中使用scope属性或在{assign}
语句中使用scope属性针对包含模板中分配的所有变量来更改此默认行为。后者可用于将值从包含模板返回到包含模板。 -
使用模板资源的语法将
{include}
文件置于$template_dir
目录外部。
选项标志
名称 | 说明 |
---|---|
nocache | 禁用此子模板的缓存 |
caching | 启用此子模板的缓存 |
inline | 如果已设置,将子模板的编译代码合并至已编译的调用模板中 |
示例
<html>
<head>
<title>{$title}</title>
</head>
<body>
{include file='page_header.tpl'}
{* body of template goes here, the $tpl_name variable
is replaced with a value eg 'contact.tpl'
*}
{include file="$tpl_name.tpl"}
{* using shortform file attribute *}
{include 'page_footer.tpl'}
</body>
</html>
{include 'links.tpl' title='Newest links' links=$link_array}
{* body of template goes here *}
{include 'footer.tpl' foo='bar'}
上面模板包含以下示例links.tpl
<div id="box">
<h3>{$title}</h3>
<ul>
{foreach from=$links item=l}
.. do stuff ...
{/foreach}
</ul>
</div>
{include 'sub_template.tpl' scope=parent}
...
{* display variables assigned in sub_template *}
{$foo}<br>
{$bar}<br>
...
上面模板包含以下示例sub_template.tpl
此包含模板不会缓存。
在此示例中,包含模板将使用 500 秒的独立缓存寿命进行缓存。
在此示例中,包含模板将独立于全局缓存设置进行缓存。
此示例将nav.tpl
的内容分配给$navbar
变量,然后在页面的顶部和底部同时输出该变量。
<body>
{include 'nav.tpl' assign=navbar}
{include 'header.tpl' title='Smarty is cool'}
{$navbar}
{* body of template goes here *}
{$navbar}
{include 'footer.tpl'}
</body>
此示例包含相对于当前模板目录的另一个模板。
{include 'template-in-a-template_dir-directory.tpl'}
{include './template-in-same-directory.tpl'}
{include '../template-in-parent-directory.tpl'}
{* absolute filepath *}
{include file='/usr/local/include/templates/header.tpl'}
{* absolute filepath (same thing) *}
{include file='file:/usr/local/include/templates/header.tpl'}
{* windows absolute filepath (MUST use "file:" prefix) *}
{include file='file:C:/www/pub/templates/header.tpl'}
{* include from template resource named "db" *}
{include file='db:header.tpl'}
{* include a $variable template - eg $module = 'contacts' *}
{include file="$module.tpl"}
{* wont work as its single quotes ie no variable substitution *}
{include file='$module.tpl'}
{* include a multi $variable template - eg amber/links.view.tpl *}
{include file="$style_dir/$module.$view.tpl"}