Yii2使用主题功能实现多端匹配

首先在项目配置文件config/main.php中配置主题配置

'as theme' => [
      'class' => 'frontend\components\ThemeControl',
    ],

* 该配置项与components同级

然后在frontend\components目录下创建ThemeControl.php文件内容如下:

<?php
namespace frontend\components;

use Yii;
use yii\base\Object;
use yii\base\ActionFilter;
class ThemeControl extends ActionFilter{
    public function init()
    {
        if(Yii::$app->devicedetect->isMobile())
        {
            $theme = "mobile";
        }else{
            $theme = "pc";
        }
        Yii::$app->view->theme = Yii::createObject([
            'class' => 'yii\base\Theme',
            'pathMap' => [
                '@app/views' => [
                    "@app/views/{$theme}",
                ]
            ]
        ]);
    }
}

需要安装alexandernst/yii2-device-detect多端检测扩展

composer require alexandernst/yii2-device-detect

配置文件中配置使用

'bootstrap' => ['devicedetect'],
'components' => [
  'devicedetect' => [
    'class' => 'alexandernst\devicedetect\DeviceDetect'
  ],
]

OK,到这里就可以在相对应的视图文件目录中创建视图文件