{include}

{include}用于载入其他模板到当前模板中。 在包含模板中可用的变量,载入后在当前模板仍然可用。

Attributes:

参数名称 类型 必选参数 默认值 说明
file string Yes n/a 包含载入的文件名
assign string No n/a 将包含的文件内容赋值给变量
cache_lifetime integer No n/a 单独开启被包含模板的缓存时间
compile_id string/integer No n/a 单独设置被包含模板的编译ID
cache_id string/integer No n/a 单独设置被包含模板的缓存ID
scope string No n/a 定义被包含模板的赋值变量作用范围: 'parent','root' 或 'global'
[var ...] [var type] No n/a 传递到包含模板的变量

可选标记:

名称 说明
nocache 关闭包含模板的缓存
caching 打开包含模板的缓存
inline 设置成true时,在编译时把包含模板的内容也合并到当前模板的编译文件中。

Example 7.46. 简单 {include} 例子


<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>

  

Example 7.47. {include} 传递变量


{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>


Example 7.48. {include} 作用范围示例

在包含的模板内赋值的变量,在包含模板内可见。


{include 'sub_template.tpl' scope=parent}
...
{* display variables assigned in sub_template *}
{$foo}<br>
{$bar}<br>
...

  

包含了下面的 sub_template.tpl 模板


...
{assign var=foo value='something'}
{assign var=bar value='value'}
...


Example 7.49. {include} 关闭缓存

包含模板将不被缓存


{include 'sub_template.tpl' nocache}
...

  

Example 7.50. {include} 单独的缓存时间

下面例子包含模板将单独设置缓存时间500秒。


{include 'sub_template.tpl' cache_lifetime=500}
...

  

Example 7.51. {include}开启缓存

下面的例子包含模板的缓存将独立于全局模板缓存设置之外。


{include 'sub_template.tpl' caching}
...

  

Example 7.52. {include} 和赋值变量

下面的例子将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>

   

Example 7.53. {include} 相对路径

下面的例子包含的模板文件都是相对当前模板的目录。


   {include 'template-in-a-template_dir-directory.tpl'}
   {include './template-in-same-directory.tpl'}
   {include '../template-in-parent-directory.tpl'}

    

Example 7.54. 各种 {include} 资源例子


{* 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"}

  

参见 {include_php}, {insert}, {php}, 模板资源模板组件化.