Sian 发表于 2016-1-27 22:30:30

模板引擎Smarty以插件形式扩展修饰器、模板函数、块函数

本帖最后由 Sian 于 2016-1-27 22:33 编辑

1、通过 $smarty->addPluginsDir(ROOT."/saplugins");      // 增加插件目录<?php
      define(ROOT, dirname(__FILE__));
      include ROOT.'/libs/Smarty.class.php';
      $smarty = new Smarty;
      // 设置模板路径,默认路径为当前php文件所在目录下的templates目录
      $smarty->setTemplateDir(ROOT."/templates");
      // 添加模板路径
//         $smarty->addTemplateDir("./Home");
      // 设置编译文件路径,默认路径为当前php文件所在目录下的templates_c目录
      $smarty->setCompileDir(ROOT."/templates_c");
      // 增加插件目录
      $smarty->addPluginsDir(ROOT."/saplugins");
      // 设置定界符
//         $smarty->setLeftDelimiter("{");
      // 设置配置文件目录
      $smarty->setConfigDir(ROOT."/config");
2、在saplugins目录下分别创建修饰器、模板函数、块函数的三个php文件(命名有讲究)

modifier.sa_style.php<?php
        // 自定义修饰器,严格要求格式smarty_modifier_ + 变量调节器名称
        // 第一个参数一定要是被修饰的字符串,后续的多个参数均可自定义
        function smarty_modifier_sa_style($str, $color, $size){
                return "<font color='$color' size='$size'>$str</font>";
        }
function.sa_echo.php<?php
        // 自定义函数,严格要求格式smarty_function + 模板函数名称
        // 只有两个参数,第一个参数为参数数组(关联数组),第二个参数为smarty对象
        function smarty_function_sa_echo($args, $smarty){
                return '<font size="'.$args['size'].'" color="'.$args['color'].'">'.$args['content'].'</font>';
        }
block.sa_block.php<?php
        // 自定义块函数,严格要求格式smarty_block + 块函数名称
        // 固定4个参数,第一个为参数数组,第二个为块之间内容,第三个为smarty对象,第四个为起始标记
        function smarty_block_sa_block($args, $content, $smarty, &$repeat){
                // 该函数会被调用两次,第一次content为空,repeat为真,第二次content为实际内容,repeat为假代表标签结束
                if($repeat)return;
                return '<font size="'.$args['size'].'" color="'.$args['color'].'">'.$content.'</font>';
        }
3、模板调用{$value|sa_style:blue:6}<br/>
{sa_echo content="Hello PHP!" size="6" color="red"}<br/>
{sa_block size="6" color="green"}Hello World!{/sa_block}<br/>
4、效果展示




页: [1]
查看完整版本: 模板引擎Smarty以插件形式扩展修饰器、模板函数、块函数