扩展模板系统


在cp中使用第三方模板系统

使用第三方PHP模版系统

以添加Smarty为例,从http://www.smarty.net/download下载你熟悉的smarty版本到项目根目录的lib中,本例以Smarty-3.1.17为例,新建一个SmartyView控制器继在你的视图控制器目录,使之承至CoreView类

1. 扩展视图控制器

扩展视图控制器

namespace app\web\views;

use Cross\MVC\View;

class SmartyView extends View
{
    function __construct()
    {
        parent::__construct();
        Loader::import("::lib/Smarty-3.1.17/libs/Smarty.class.php");
        $this->smarty = new Smarty;

        $this->smarty->debugging = true;
        $this->smarty->caching = true;
        $this->smarty->cache_lifetime = 120;
    }
}

2. 使用

调用第三方模板系统提供的方法

namespace app\web\views;

class MainView extends SmartyView
{
    function index($data = array())
    {
        $this->smarty->assign("name", $data['name']);
        $this->smarty->assign("FirstName",array("John","Mary","James","Henry"));
        $this->smarty->assign("LastName",array("Doe","Smith","Johnson","Case"));
        $this->smarty->assign("contacts", array(
				array("phone" => "1", "fax" => "2", "cell" => "3"),
                array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234")
			));

        $this->smarty->display( $this->tpl("main/index") );
    }
}

使用JS模板引擎

以添加artTemplate模板引擎为例, 从https://github.com/aui/artTemplate下载最新版本,放在htdocs/static/lib目录下.

1. 引入JS模板引擎

修改模板根目录下的default.layer.php文件,在head部分中加入引擎的连接

<script src="<?php echo $this->res("lib/artTemplate/dist/template-simple.js") ?>"></script>

为content所在的父级div添加一个id属性

<div id="layer-content">
    <?php echo isset($content)?$content:'暂无内容' ?>
</div>

</body>前添加如下JS代码

<script type="text/javascript">
    var html = template.render('layer-content', <?php echo isset($jsonData)?$jsonData:'{}' ?>);
    document.getElementById('layer-content').innerHTML = html;
</script>

2. 使用方法

在视图视图控制器类中使用. 通过$this->set()把模板引擎需要的数据传送到layer.

namespace app\web\views;

use Cross\MVC\View;

class MainView extends View
{
    function index($data = array())
    {
        $this->set(array(
           'jsonData' =>  json_encode($data)
        ));

        include $this->tpl("main/index");
    }
}

>以上两种方式都保留了CP的layer功能.