Our Work

Themeing yii2 application

Updated 2 years, 5 months and 7 days ago

IN Yii 1.X we have themes, but its missing in yii 2.0, so how you can add themes to your Yii Web applications. Before we go further lets know what is Theming? Theming is a systematic way of customizing the outlook of pages in a Web application. By applying a new theme, the overall appearance of a Web application can be changed instantly and dramatically.

If in your Yii 2.0 Web application if you want to allow the user to choose theme and based on that you want to apply the theme we may have to few overrides and going forward we will load this at the YII app start.

Extending YII web application:- 

app/components/CustomerApplication.php
class CustomApplication extends \yii\web\Application{
    public function init(){
    parent::init();
    }
}
In Index.php
<?php 
-----
--- all other code to include config files --
$application = new app\components\CustomApplication($config);
$application->run();


Create new theme folder in Yii app directory along with default layout files.. 

    app/themes/customTheme/   

 Generic usage we need to create new alias for theme path, we can add this to Custom application init();

Yii::setAlias('@customtheme',$this->getBasePath().'/themes/customTheme');

In Custom Application init we can add following code to implement theme..   

$this->view->theme = new \yii\base\Theme([
                            'pathMap' => ['@app/views' => '@customtheme/views'],
    ]);


Now all layouts can be loaded from our theme folder... but controller view also if you want to load from theme folder we can do using 

Custom Layouts view action:- Let's consider we have page model which we need you give ability to change layout for page..just like CMS functionality.. So we need to provide user  change layouts like twocolumn and threecolumn

Create templates folder in theme and keep all your layouts in that folder like twocolumn.php threecolumn.php

For this we need to give attribute to Pages model PageTemplate which will stored in db.. PageTemplate value will be assigned file name from templates folder from theme. 

and pageController action view.. 

public function actionview($id){
    $model = $this->findModelSlug($slug);
        if ($model->PageTemplate!==null) {
                            $layout = "templates/".$model->PageTemplate;
                    } else {
                        $layout = 'main';
                    }
}

 

Related Posts