Yii2 Views & Layouts

Introduction

In Yii2, Views and Layouts are responsible for rendering the user interface. Views display page-specific content, while Layouts define the overall structure of a page. Yii2 provides a flexible system that allows customization of views and layouts, including module-specific themes and layouts.

This guide covers:

  • Understanding views in Yii2
  • Using different rendering methods
  • Working with layouts and overriding them
  • Implementing themes
  • Handling separate views and layouts in modules

1. Understanding Yii2 Views

Views are PHP files that primarily contain HTML mixed with PHP code to present data. They are stored in the views/ directory, typically within the respective controller's folder.

View File Structure

views/
 ├── site/
 │   ├── index.php
 │   ├── about.php
 ├── layouts/
 │   ├── main.php
 │   ├── admin.php
 ├── partials/
 │   ├── _menu.php
 │   ├── _sidebar.php

Rendering Views

Using render()

Renders a view with a layout.

public function actionIndex()
{
    $message = "Welcome to Yii2";
    return $this->render('index', ['message' => $message]);
}

Using renderPartial()

Renders a view without a layout.

return $this->renderPartial('index', ['message' => $message]);

Using renderAjax()

Optimized for AJAX responses, excludes unnecessary layouts.

return $this->renderAjax('index', ['message' => $message]);

Using renderFile()

Renders a view file from a custom path.

return $this->renderFile('@app/views/custom/example.php', ['data' => $data]);

Using renderContent()

Renders a raw string as a response.

return $this->renderContent("<h1>Hello, Yii2!</h1>");

2. Yii2 Layouts

A layout is a wrapper that defines the common structure for multiple views.

Default Layout

By default, Yii2 uses views/layouts/main.php.

<?php $this->beginPage(); ?>
<!DOCTYPE html>
<html>
<head>
    <title><?= $this->title ?></title>
</head>
<body>
    <header>
        <h1>My Yii2 Application</h1>
    </header>
    <main>
        <?= $content ?>
    </main>
    <footer>
        <p>&copy; <?= date('Y') ?> My Company</p>
    </footer>
</body>
</html>
<?php $this->endPage(); ?>

Changing Layout for a Controller

class SiteController extends Controller
{
    public $layout = 'admin';
}

Disabling Layout in an Action

public function actionNoLayout()
{
    $this->layout = false;
    return $this->render('simple');
}

3. Implementing Themes in Yii2

Themes allow overriding view files dynamically. They are configured in the application component.

Defining a Theme in config/web.php

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

Now, Yii2 will load views from themes/custom/views instead of views/.


4. Handling Separate Views and Layouts in Modules

Each Yii2 module can have its own views, layouts, and themes.

Module Directory Structure

modules/
 ├── admin/
 │   ├── controllers/
 │   │   ├── DefaultController.php
 │   ├── views/
 │   │   ├── default/
 │   │   │   ├── index.php
 │   ├── layouts/
 │   │   ├── main.php
 │   ├── themes/
 │   │   ├── assets/
 │   │   │   ├── views/

Overriding Views and Layouts in a Module

In the module’s init() method, define a separate view path:

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

Now, all views inside the admin module will be loaded from modules/admin/themes/assets/views/ instead of the default views/ directory.

Setting a Separate Layout for the Module

In Module.php, set the layout path:

public $layoutPath = '@app/modules/admin/layouts';
public $layout = 'main';

Now, the module will use modules/admin/layouts/main.php instead of views/layouts/main.php.


5. Best Practices for Views & Layouts

Keep Views Clean

Avoid writing complex logic in views. Instead, prepare data in the controller.

// Controller
$data = strtoupper($model->name);
return $this->render('index', ['data' => $data]);

Use Partials for Reusability

<?= $this->render('//partials/_menu'); ?>

Use Layouts for Consistency

Define a default layout for a consistent page structure, and separate frontend/admin layouts.


Summary

FeatureMethod / Usage
Render a Viewreturn $this->render('index', ['data' => $data]);
Render Without Layoutreturn $this->renderPartial('index');
Render AJAX Viewreturn $this->renderAjax('index');
Render from Filereturn $this->renderFile('@app/views/custom.php');
Render a Partial View<?= $this->render('//partials/_menu'); ?>
Change Layout in Controller$this->layout = 'admin';
Disable Layout$this->layout = false;
Define a Theme@app/themes/custom/views/
Separate Module ViewsOverride viewPath and layoutPath in Module.php

Conclusion

Yii2’s Views and Layouts system provides a structured approach to rendering content. By properly utilizing layouts, themes, and module-specific views, developers can maintain clean, scalable, and reusable templates across different parts of an application.