Table of Contents
模板可以是各种不同的来源提供的。
当你display() 或者
fetch()一个模板,
又或者当你包含一个模板到另一个模板中的时候,你需要提供一个资源类型、路径及模板名。
如果没有明确指明资源类型,则将假定是使用
$default_resource_type
(默认是“file”)。
Smarty通常运行在内置的、基于文件系统的模板资源上。
默认资源是file:。
如果修改了$default_resource_type
那么资源关键字file:就必须要指明。
如果找不到需要的模板文件,那么 $default_template_handler_func将会被调用。
在Smarty 3.1开始,除非开启了
$use_include_path配置,否则文件资源不会再搜索
include_path
的路径了。
Smarty从$template_dir设置的目录中,
获取模板文件资源。
多个模板目录将以在数组中的顺序进行搜索,在寻找到第一个匹配的模板时将返回。
Example 16.1. 使用$template_dir
<?php
$smarty->display('index.tpl');
$smarty->display('file:index.tpl'); // 同上
?>
模板中使用
{include file='index.tpl'}
{include file='file:index.tpl'} {* 同上 *}
Smarty 3.1 提供“归类符号”来定义$template_dir中的特定元素。
此特性可允许网站中使用和更好地管理多个模板集合。
“归类符号”可以用在任何定义了file:资源类型的地方。
Example 16.2. 特定的$template_dir
<?php
// 设置模板目录
$smarty->setTemplateDir(array(
'./templates', // element: 0, index: 0
'./templates_2', // element: 1, index: 1
'10' => 'templates_10', // element: 2, index: '10'
'foo' => 'templates_foo', // element: 3, index: 'foo'
));
/*
假定模板目录结构如下:
./templates/foo.tpl
./templates_2/foo.tpl
./templates_2/bar.tpl
./templates_10/foo.tpl
./templates_10/bar.tpl
./templates_foo/foo.tpl
*/
// 正常读取
$smarty->display('file:foo.tpl');
// 将载入 ./templates/foo.tpl
// 默认使用数字下标
$smarty->display('file:[1]foo.tpl');
// 将载入 ./templates_2/foo.tpl
// 使用字符串的下标('10'看起来像数字下标,但却是有单引号的字符串)
$smarty->display('file:[10]foo.tpl');
// 将载入 ./templates_10/foo.tpl
// 使用字符串的下标
$smarty->display('file:[foo]foo.tpl');
// 将载入 ./templates_foo/foo.tpl
// 使用 "未知" 数字下标 (用元素的数字)
$smarty->display('file:[2]foo.tpl');
// 将载入 ./templates_10/foo.tpl
?>
模板中调用
{include file="file:foo.tpl"}
{* 将载入 ./templates/foo.tpl *}
{include file="file:[1]foo.tpl"}
{* 将载入 ./templates_2/foo.tpl *}
{include file="file:[foo]foo.tpl"}
{* 将载入 ./templates_foo/foo.tpl *}
在$template_dir之外的模板,
file:将需要使用绝对路径来获取模板。
当Security开启,
在$template_dir之外的模板是不允许读取的,除非你将这些目录都设置在$secure_dir中。
Example 16.3. 任意目录的模板
<?php
$smarty->display('file:/export/templates/index.tpl');
$smarty->display('file:/path/to/my/templates/menu.tpl');
?>
模板中:
{include file='file:/usr/local/share/templates/navigation.tpl'}