在YII2中使用Jade模板引擎

  • 发布时间:2017-04-12 09:31:47
  • 作者:jason8482
  • 标签:PHP,Yii2,Jade

Jade是一个高性能的模板引擎,他深受Haml的影响。最初是由JavaScript发展起来供nodejs使用。也有其他语言的实现,可以实现前后端渲染的统一。


今天想要介绍的是在YII2框架中配置jade模板引擎来提高开发效率:


环境介绍:

YII2.0

PHP5.4+


安装:

我们推荐使用更加便捷的composer工具来进行安装:

composer require conquer/jade "*"

或者在composer.json中添加

"conquer/jade" : "*"


使用composer进行安装完成后。


在YII2中配置jade引擎:

web.php中修改如下

    //....
    'components' => [
        'view' => [       
            'defaultExtension' => 'jade', // Set jade as default to use base view file names without extension.
            'renderers' => [
                'jade' => [
                    'class' => 'conquer\jade\JadeRenderer',
                    'cacheDuration' => 0, // seconds. 0 - compile every time
                ],
            ],
        ],
    ],
];


实例:

Controller:

class SiteController extends Controller
{
    // if you do not specify a defaultExtension, you should specify it here
    $layout = 'main.jade';
    ...
    public function actionIndex()
    {
        return $this->render('index', []);
        // or
        // return $this->render('index.jade', []);
    }
}


Main layout:

-
    use yii\bootstrap\Html;
    use assets\AppAsset;
    
    
    AppAsset::register($this);
-$this->beginPage()
doctype html
html(lang=Yii::$app->language)
    // BEGIN HEAD
    head
        meta(charset="utf-8")
        title
            != Html::encode($this->title)
        meta(http-equiv="X-UA-Compatible", content="IE=edge")
        meta(content="width=device-width initial-scale=1", name="viewport")
        != Html::csrfMetaTags()
        meta(content="", name="description")
        meta(content="", name="author")
        link(rel="shortcut icon", href="/favicon.ico" rel="external nofollow" )
        - $this->head()
    // END HEAD
    body(class=$this->params['body-class'])
        - $this->beginBody()
        != $content
        - $this->endBody()
    - $this->endPage()


子页面:

-
    use yii\web\YiiAsset;
    use yii\base\Widget;
    use yii\bootstrap\Html;
    use yii\helpers\Url;
    
    
    $this->params['body-class'] = 'page-header-fixed page-sidebar-closed-hide-logo';
    YiiAsset::register($this);

- $this->beginContent('@views/layouts/main.jade');

// BEGIN HEADER & CONTENT DIVIDER
include header

.clearfix
// END HEADER & CONTENT DIVIDER
// BEGIN CONTAINER
.page-container
    // sidebar.jade is placed at @views/layouts/partials/sidebar.jade
    // jade engine just puts rendered content here
    include partials/sidebar
    != $content
// END CONTAINER
include partials/footer

- $this->endContent();



最终将按照jade语法输出html页面。

jade相关语言请参考https://segmentfault.com/a/1190000000357534