Yii2-自适应切换模板

1、创建behavior

// frontend/behaviors/MobileBehavior.php

class MobileBehavior extends \yii\base\Behavior
{
    public function events()
        {
            return [
                    \yii\web\Controller::EVENT_BEFORE_ACTION => 'beforeAction'
                ];
        }

        public function beforeAction($event)
        {
            if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') {
                    $event->sender->module->setViewPath($event->sender->module->getBasePath().DIRECTORY_SEPARATOR.'H5Views');
                } 
        }
}

2、建一个基类BaseController.php

// frontend/controllers/BaseController.php
class BaseController extends \yii\web\Controller
{
    public function behaviors()
        {
            return [
                    \frontend\behaviors\MobileBehavior::className()
                ];
        }

        // 其他action
}

其他控制器继承BaseController。
3、在frontend下面创建H5Views, H5模板文件放在这里面就OK了。

上一篇:ci框架子类继承父类时,报错Fatal error: Class ‘BaseController‘ not found in C:\xampp\htdocs


下一篇:java基础知识查漏 四