How to apply a layout to an AJAX update

You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#2) »

  1. The background
  2. The problem
  3. The solution

The background

The template system in Yii is quite flexible. By default you have three layers of content:

  1. The Main template holds the header, main navigation and footer
  2. One or more layout files holds the column setup, sub navigation etc.
  3. The view files hold the actual page content.

When you load a page, the render method does the following:

  1. Renders the view file
  2. Decorates the view with the layout
  3. Apply the template to the layout.

An AJAX call is normally much more lightweight. If you use renderPartial with the processOutput parameter set to false, the layout and template is never added to the output.

The problem

Sometimes, however, it can be useful to also switch the layout on an AJAX update, without having to load the whole page with all CSS, JS etc.

The solution

The following code snippet from a controller action specifies the view to be rendered and the layout to be applied. For an AJAX update, a renderPartial is used to generate and return the view file. Then a CContentDecorator is created to apply the layout.

switch ($page) {
            case 1:
                $this->layout = '//layouts/teamPlayers';
                $view = 'dashboardPlayers';
                break;

            case 2:
                $this->layout = '//layouts/teamEdit';
                $view = 'dashboardEdit';
                break;

            default:
                Yii::app()->end();
        }

        if (Yii::app()->request->isAjaxRequest) {
            $output = $this->renderPartial($view, $params, true, false);

            $params['template'] = '';
            $ContentDecorator = new CContentDecorator;
            $ContentDecorator->view = $this->layout;
            $ContentDecorator->data = $params;
            $ContentDecorator->processOutput($output);
        } else {
            $this->render($view, $params);
        }

Finally the layout file(s) (located in protected\views\layouts) are modified by replacing the beginContent statement with the following code snippet:

<?php
if (isset($_data_['template'])) {
    $this->beginContent($_data_['template']);
} else {
    $this->beginContent('//layouts/dashboard');
}
?>

1 0
4 followers
Viewed: 16 456 times
Version: Unknown (update)
Category: How-tos
Tags: AJAX, views
Written by: trond
Last updated by: CeBe
Created on: Feb 11, 2014
Last updated: 10 years ago
Update Article

Revisions

View all history

Related Articles