2024年6月14日发(作者:)

Twig模板引擎使用笔记

安装配置

1. 新建一个目录 libs

2. 在该目录下新建文件 ,往该文件写入以下内容:

3. {

4. "require": {

5. "twig/twig": "1.*"

6. }

7. }

8. 在 libs 目录上执行 composer install 安装 Twig(前提是已安装 Composer 包管理器)

9. 在 libs 上级目录新建三个文件夹:templates、templates_c、web,其中 templates 用来存放模板

文件,templates_c 用来存放编译缓存文件,web 用来存放 PHP 源文件

10. 在 libs 上级目录新建文件 公共文件,内容如下:

11. // 引用 Composer 自动加载文件

12. require_once dirname(__FILE__).'/libs/vendor/';

13. // 注册 Twig 加载器

14. Twig_Autoloader::register();

15. // 设置基本的配置项

16. $loader = new Twig_Loader_Filesystem(dirname(__FILE__).'/templates');

17. $twig = new Twig_Environment($loader, array(

18. 'cache' => dirname(__FILE__).'/templates_c',

19. 'auto_reload' => true

20. ));

21. 后续使用时,只需让 web 目录下的 PHP 文件引用该公共文件,且在 templates 目录下放置好

对应的模板即可,引用公共文件的语句为:require_once dirname(dirname(__FILE__)).'/';

22. 基本的模板渲染语句:echo $twig->render('', array('name' => 'Ruchee'));

可用符号

== != < > >= <= + - ~ * / // % ** | [] . .. and or not in is b-and b-or b-xor