Chapter 16. 资源

模板可以是各种不同的来源提供的。 当你display() 或者 fetch()一个模板, 又或者当你包含一个模板到另一个模板中的时候,你需要提供一个资源类型、路径及模板名。 如果没有明确指明资源类型,则将假定是使用 $default_resource_type (默认是“file”)。

文件资源

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

  1. <?php
  2. $smarty->display('index.tpl');
  3. $smarty->display('file:index.tpl'); // 同上
  4. ?>
  5.  

模板中使用

  1. {include file='index.tpl'}
  2. {include file='file:index.tpl'} {* 同上 *}
  3.  

特定的$template_dir

Smarty 3.1 提供“归类符号”来定义$template_dir中的特定元素。 此特性可允许网站中使用和更好地管理多个模板集合。

“归类符号”可以用在任何定义了file:资源类型的地方。


Example 16.2. 特定的$template_dir

  1. <?php
  2.  
  3. // 设置模板目录
  4. $smarty->setTemplateDir(array(
  5. './templates', // element: 0, index: 0
  6. './templates_2', // element: 1, index: 1
  7. '10' => 'templates_10', // element: 2, index: '10'
  8. 'foo' => 'templates_foo', // element: 3, index: 'foo'
  9. ));
  10.  
  11. /*
  12. 假定模板目录结构如下:
  13. ./templates/foo.tpl
  14. ./templates_2/foo.tpl
  15. ./templates_2/bar.tpl
  16. ./templates_10/foo.tpl
  17. ./templates_10/bar.tpl
  18. ./templates_foo/foo.tpl
  19. */
  20.  
  21. // 正常读取
  22. $smarty->display('file:foo.tpl');
  23. // 将载入 ./templates/foo.tpl
  24.  
  25. // 默认使用数字下标
  26. $smarty->display('file:[1]foo.tpl');
  27. // 将载入 ./templates_2/foo.tpl
  28.  
  29. // 使用字符串的下标('10'看起来像数字下标,但却是有单引号的字符串)
  30. $smarty->display('file:[10]foo.tpl');
  31. // 将载入 ./templates_10/foo.tpl
  32.  
  33. // 使用字符串的下标
  34. $smarty->display('file:[foo]foo.tpl');
  35. // 将载入 ./templates_foo/foo.tpl
  36.  
  37. // 使用 "未知" 数字下标 (用元素的数字)
  38. $smarty->display('file:[2]foo.tpl');
  39. // 将载入 ./templates_10/foo.tpl
  40.  
  41. ?>
  42.  

模板中调用

  1. {include file="file:foo.tpl"}
  2. {* 将载入 ./templates/foo.tpl *}
  3.  
  4. {include file="file:[1]foo.tpl"}
  5. {* 将载入 ./templates_2/foo.tpl *}
  6.  
  7. {include file="file:[foo]foo.tpl"}
  8. {* 将载入 ./templates_foo/foo.tpl *}
  9.  

任意目录的模板

$template_dir之外的模板, file:将需要使用绝对路径来获取模板。

Note

Security开启, 在$template_dir之外的模板是不允许读取的,除非你将这些目录都设置在$secure_dir中。


Example 16.3. 任意目录的模板

  1. <?php
  2. $smarty->display('file:/export/templates/index.tpl');
  3. $smarty->display('file:/path/to/my/templates/menu.tpl');
  4. ?>
  5.  

模板中:

  1. {include file='file:/usr/local/share/templates/navigation.tpl'}
  2.  

Windows文件路径

如果使用Windows的机器,那么文件路径将以驱动盘符(C:)开头。 确保file:的路径避免命名空间冲突,达到需要的结果。


Example 16.4. 使用windows的文件路径

  1. <?php
  2. $smarty->display('file:C:/export/templates/index.tpl');
  3. $smarty->display('file:F:/path/to/my/templates/menu.tpl');
  4. ?>
  5.  

在模板中:

  1. {include file='file:D:/usr/local/share/templates/navigation.tpl'}
  2.  

原文: https://www.smarty.net/docs/zh_CN/resources.tpl