Smarty文件资源
文件资源
Smarty通常运行在内置的、基于文件系统的模板资源上。 默认资源是file:。 如果修改了$default_resource_type 那么资源关键字file:就必须要指明。
如果找不到需要的模板文件,那么 $default_template_handler_func将会被调用。
说明
在Smarty 3.1开始,除非开启了 $use_include_path配置,否则文件资源不会再搜索 include_path 的路径了。
$template_dir目录
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'} {* 同上 *}
特定的$template_dir
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:将需要使用绝对路径来获取模板。
Note
当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'}
Windows文件路径
如果使用Windows的机器,那么文件路径将以驱动盘符(C:)开头。 确保file:的路径避免命名空间冲突,达到需要的结果。
Example 16.4. 使用windows的文件路径
<?php
$smarty->display('file:C:/export/templates/index.tpl');
$smarty->display('file:F:/path/to/my/templates/menu.tpl');
?>
在模板中:
{include file='file:D:/usr/local/share/templates/navigation.tpl'}