Yii2 Theme Integration

Introduction

Integrating themes in Yii2 allows developers to customize the appearance of their applications efficiently. Yii2 provides built-in mechanisms for theme integration, enabling the separation of frontend assets and layout files from the core logic.

This tutorial covers:

  • Default method of theme integration
  • Recommended method using Asset Bundles
  • Setting up path mappings for themes

Default Method of Theme Integration

The default way to integrate a theme in Yii2 is by configuring the theme component inside the config/web.php file.

Example Configuration:

'components' => [
    'view' => [
        'theme' => [
            'pathMap' => [
                '@app/views' => '@app/themes/custom',
            ],
            'baseUrl' => '@web/themes/custom',
        ],
    ],
],

Explanation:

  • pathMap defines where Yii2 should look for overridden view files.
  • baseUrl specifies the URL path for theme assets.
  • Place the new theme files inside @app/themes/custom.

Now, when Yii2 renders views, it will first check @app/themes/custom before falling back to @app/views.


Recommended Method: Using Asset Bundles

A more modular and maintainable approach to theme integration is by using Asset Bundles. This method provides better performance and control over theme assets.

Creating an Asset Bundle for a Theme

Create a new asset bundle file at assets/HomeAsset.php:

namespace app\assets;

use yii\web\AssetBundle;

class HomeAsset extends AssetBundle
{
    public $sourcePath = '@app/themes/home/assets/';
    public $css = [
        'css/prettyPhoto.css',
        'css/main.css',
    ];
    public $js = [
        'js/jquery.prettyPhoto.js',
        'js/main.js',
        'js/jquery.placeholder.min.js',
        'js/handlebars-1.0.0.beta.6.js',
        'js/core.js',
    ];
 	public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap4\BootstrapAsset',
    ];}

Registering the Theme Asset Bundle in Views

In your layouts/main.php or any view file where you want to apply the theme, register the asset bundle:

use app\assets\HomeAsset;
HomeAsset::register($this);

Benefits of Using Asset Bundles:

  • Better Performance: Yii2 can optimize asset publishing and minify CSS/JS files.
  • Modularity: Each theme can have its own separate asset bundle.
  • Efficient Management: Developers can easily switch between different themes.

Updating main.php Layout Files for Theme Assets

When integrating a new theme or updating an existing one, ensure that the main.php layout file correctly registers the theme's asset bundle.

Example layouts/main.php Update:

<?php

/** @var yii\web\View $this */
/** @var string $content */

use app\assets\HomeAsset;
use app\widgets\Alert;
use app\widgets\BreadcrumbsCustom;
use yii\bootstrap4\Html;

HomeAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
    <meta charset="<?= Yii::$app->charset ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <?php $this->registerCsrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>
</head>
<body>
    <?php $this->beginBody() ?>
    <div class="page">
        <div>
            <?= $this->render('_header') ?>
            <?= $this->render('_navbar') ?>
        </div>
        <div class="main-content app-content">
            <div class="main-container container-fluid">
                <?= BreadcrumbsCustom::widget([]) ?>
                <?= Alert::widget() ?>
                <?= $content ?>
            </div>
        </div>
        <div class="main-footer">
            <div class="col-md-12 text-center">
                <div class="container-fluid">
                    Copyright © <?= date('Y') ?> Company. All Rights Reserved
                </div>
            </div>
        </div>
    </div>
    <a href="#top" id="back-to-top"><i class="las la-arrow-up"></i></a>
    <?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

Key Updates in main.php:

  • Ensure HomeAsset is registered before the beginPage() call.
  • Meta tags and CSRF protection are included.
  • Header and navbar sections are dynamically rendered.
  • Breadcrumbs and alerts are displayed above the content.
  • Footer is included at the bottom for a consistent layout.

By following these steps, your Yii2 theme integration remains modular, organized, and easily updatable.


Setting Up Theme Path Mapping in Modules

If you are using Yii2 Modules and want each module to have its own views and layouts, you can override the default view component inside the module’s init() method.

Example:

namespace app\modules\admin;

class Module extends \yii\base\Module
{
    public function init()
    {
        parent::init();
        \Yii::$app->view->theme = new \yii\base\Theme([
            'pathMap' => ['@app/views' => '@app/modules/admin/themes/admin'],
        ]);
    }
}

Explanation:

  • This ensures that all views inside the admin module will use the theme located in @app/modules/admin/themes/admin.
  • Prevents conflicts between different modules and the main application theme.

Updating main.php Layout When Integrating a New Theme

When integrating a new theme, ensure that the layout structure in layouts/main.php matches the new theme's requirements. Update the <div>, <section>, and other structural elements accordingly.

Example:

use app\assets\HomeAsset;
HomeAsset::register($this);

Also, verify that all CSS and JS files are correctly linked in HomeAsset.php. Missing or incorrect asset references can cause issues with the theme’s functionality.


Conclusion

Yii2 provides multiple ways to integrate themes, but using Asset Bundles is the recommended approach for better modularity and performance. By leveraging Yii2’s theme system, you can efficiently manage different themes and layouts in your application.