dedecms 编译式引擎开发案例

3.1 编译式模板

先来写个程序(以后root代表根目录)

root/code.php

<?php
    //利用dedecms写php时,基本都要引入common.inc.php
    require_once (dirname(__FILE__) . '/include/common.inc.php');
    //利用编译式模板所需的文件
    require_once (DEDEINC.'/dedetemplate.class.php');

//生成编译模板引擎类对象
$tpl = new DedeTemplate(dirname(__file__));
//装载网页模板
$tpl->LoadTemplate('code.tpl.htm');
//把php值传到html
$title = 'Hello World';
$tpl->SetVar('title',$title);
$tpl->Display();
//把编译好的模板缓存做成code.html,就可以直接调用
$tpl->SaveTo(dirname(__FILE__).'/code.html');
?>
root/code.tpl.htm

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=gb2312” />
<title>无标题文档</title>
</head>

<body>

{dede:var.title/} – {dede:php echo “Little”; /} –

{dede:php}
echo “Hann”;
{/dede:php}

</body>
</html>

同时,在当前目录下也生成了静态的html文件

code.html

<img src="http://www.tuicool.com/articles/RF3eimf" alt="" />
//编译式模板和标签解释的文件都放在/include/ tpllib 下,所以如果我们需要编写、实现我们自己的自定义标签,就需要按照DEDE的代码架构,在这个文件夹下添加新的标签处理代码逻辑
root/include/tpllib/plus_hello.php
<?php
if(!defined('DEDEINC')) exit('Request Error!');
/**
 * 动态模板hello标签学习原理
 *
 * @version        $Id: plus_ask.php 1 13:58 2010年7月5日Z tianya $
 * @package        DedeCMS.Tpllib
 * @copyright      Copyright (c) 2007 - 2010, DesDev, Inc.
 * @license        http://help.dedecms.com/usersguide/license.html
 * @link           http://www.dedecms.com
 */

function plus_hello(&$atts,&$refObj,&$fields)
{
    global $dsql,$_vars;

    //给出标签的属性默认参数值列表,以’,’分隔,即使不设置默认参数也要给出属性名
    $attlist = "name=";

    FillAtts($atts,$attlist); //设定属性的默认值
    FillFields($atts,$fields,$refObj); //把上级的fields传递给atts
    extract($atts, EXTR_OVERWRITE);  //解压单个文件

    //返回处理结果,以替换标签
    return 'hello1!'.$name;
}
?>

发表评论