文件模板资源 {/programmers/resources/resources-file/}
Smarty 默认内置了一个文件系统的模板资源。file: 是默认的资源。只有当$default_resource_type已经被修改,资源键 file: 才需要被指定。
如果文件资源无法找到请求的模板,将会调用 $default_template_handler_func。
注意
自 Smarty 3.1 起,文件资源不再遍历include_path,除非
$use_include_path已经被激活
从 \$template_dir 获取模板 {#templates.from.template.dir}
文件资源从 $template_dir指定的目录中提取模板源文件。目录列表按数组中出现的顺序遍历。找到的第一个模板就是要处理的模板。
<?php
$smarty->display('index.tpl');
$smarty->display('file:index.tpl'); // 同上
?>
在 Smarty 模板内部
{include file='index.tpl'}
{include file='file:index.tpl'} {* 同上 *}
从指定的 \$template_dir 获取模板 {#templates.from.specified.template.dir}
Smarty 3.1 引入了方括号语法,用于指定来自$template_dir的元素。这允许使用多套模板的网站更好地控制访问哪个模板。
方括号语法可以在任何可以指定 file: 资源类型的地方使用。
<?php
// 设置模板目录
$smarty->setTemplateDir(array(
'./templates', // 元素:0, 索引:0
'./templates_2', // 元素:1, 索引:1
'10' => 'templates_10', // 元素:2, 索引:'10'
'foo' => 'templates_foo', // 元素:3, 索引:'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
// 使用数字字符串索引
$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
?>
在 Smarty 模板内部
{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 *}
从任何目录获取模板 {#templates.from.any.dir}
在 $template_dir 之外的模板需要 file: 模板资源类型,后面跟着模板的绝对路径(以斜线开头)。
注意
在启用
Security的情况下,不允许访问$template_dir之外的模板,除非你在$secure_dir中列出这些目录。
<?php
$smarty->display('file:/export/templates/index.tpl');
$smarty->display('file:/path/to/my/templates/menu.tpl');
?>
在 Smarty 模板内部:
{include file='file:/usr/local/share/templates/navigation.tpl'}
Windows 文件路径 {#templates.windows.filepath}
如果你在使用 Windows 机器,文件路径通常在路径名的开头包含一个驱动器字母(如 C:)。请确保在路径中使用 file: 以避免命名空间冲突并得到期望的结果。
<?php
$smarty->display('file:C:/export/templates/index.tpl');
$smarty->display('file:F:/path/to/my/templates/menu.tpl');
?>
在 Smarty 模板内部:
{include file='file:D:/usr/local/share/templates/navigation.tpl'}