How to show slider only on index page in yii2

333 views Asked by At

I have an image slider in yii2 in _carousel.php. I want to render this partial form in main.php when actionIndex is called. What I did is to save rendered html code in a variable and and send to index, but it is not recognizable in main.php. How to cache it and show in main.php while in actionIndex we have:

$_carousel = $this->renderPartial('_carousel');
return $this->render('index', [
            'carousel' => $_carousel
        ]);

Something similar to code below in yii 1.4:

$this->beginClip('bannerSlideshow');
            echo $this->renderPartial('//layouts/banner');
        $this->endClip();
1

There are 1 answers

1
Nordseebaer On

main.php is your layout? When you call actionIndex() (this is your action in your controller right?) and assign the 'carousel' to the index-view of your controller you actually have what you want. You only assign 'carousel' to your view on the index site.

But you know which action is executing your layout. In your layout main.php

...
//$this->context->id //this is the current controller executed
//Combine it with the controllerId if you have more than one indexAction in your app.
if($this->context->action->id === 'index') {
    echo $this->render(/{controller}/_carousel); //your rendered carousel in main.php. 
//when you are using modules this should be
    echo $this->render(//{controller}/_carousel);
....
}

See also http://www.yiiframework.com/doc-2.0/guide-structure-views.html#accessing-data-in-views