年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 2304|回复: 0

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

[复制链接]
  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

    发表于 2016-1-27 22:30:30 | 显示全部楼层 |阅读模式
    本帖最后由 Sian 于 2016-1-27 22:33 编辑

    1、通过 $smarty->addPluginsDir(ROOT."/saplugins");        // 增加插件目录
    [PHP] 纯文本查看 复制代码
    <?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] 纯文本查看 复制代码
    <?php
    	// 自定义修饰器,严格要求格式smarty_modifier_ + 变量调节器名称
    	// 第一个参数一定要是被修饰的字符串,后续的多个参数均可自定义
    	function smarty_modifier_sa_style($str, $color, $size){
    		return "<font color='$color' size='$size'>$str</font>";
    	}

    function.sa_echo.php
    [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] 纯文本查看 复制代码
    <?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、模板调用
    [HTML] 纯文本查看 复制代码
    {$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、效果展示

    屏幕快照 2016-01-27 下午10.26.59.png


    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-3-29 22:36 , Processed in 0.056822 second(s), 21 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表