Karate_Dog
Karate_Dog

Reputation: 1277

Yii 2.0 Loading css and js in renderPartial

How can I load css and javascript files if I render a page using renderPartial() ? The problem is that I NEED my page to be mobile responsive. This does not seem to be a problem when I use render()

I tried including the boostrap css and js in my page, but It still did not work.

I have included the css and js in my page :

<link rel="stylesheet" href="<?= Yii::getAlias('@web/css/bootstrap.min.css')?> ">
<link rel="stylesheet" href="<?= Yii::getAlias('@web/css/sb-admin.css')?>">
<link rel="stylesheet" href="<?= Yii::getAlias('@web/css/site.css')?>">
<link rel="stylesheet" href="<?= Yii::getAlias('@web/css/jquery-ui.css')?>">

And

<script type="text/javascript" src="<?= Yii::getAlias('@web/js/jquery.js')?>"></script>
<script type="text/javascript" src="<?= Yii::getAlias('@web/js/bootstrap.min.js')?>"></script>

And in my controller :

return $this->renderPartial('create', [
                        'model' => $model,
            ]);

What Am I missing ?

Upvotes: 3

Views: 7254

Answers (5)

ScaisEdge
ScaisEdge

Reputation: 133400

renderPartial() does not use the layout. If you need the CSS and JS you can create a layout suitable for you in the directory views/layouts and call it in your action by entering:

$this->layout = 'yourLayout';
return $this->render('yourForm', [
    'model' => $yourModel,
]); 

Upvotes: 6

Ziya Vakhobov
Ziya Vakhobov

Reputation: 465

Use renderJsFile and renderCssFile

$this->registerJsFile(
    '@web/js/main.js',
    ['depends' => [\yii\web\JqueryAsset::className()]]
);

$this->registerCssFile("@web/css/themes/black-and-white.css", [
    'depends' => [\yii\bootstrap\BootstrapAsset::className()],
    'media' => 'print',
], 'css-print-theme');

just change depends to what you need. Here is full documentation link

Upvotes: 0

Toms Kovkājevs
Toms Kovkājevs

Reputation: 11

If you are using renderAjax and If you know you do not need to load jQuery and/or JUI within the view file, just put at the end:

unset($this->assetBundles['yii\web\YiiAsset']);
unset($this->assetBundles['yii\web\JqueryAsset']);

so the renderAjax method loads just the assets that are left..

Upvotes: 1

Kalpesh Desai
Kalpesh Desai

Reputation: 1421

use renderAjax() instead of renderPartial()... its works

the different between renderPartial() and renderAjax() is renderAjax() also load js and css(asset bundle and its dependency) without layout while renderPartial() does not load css and js as well as layout..:)

you may use

return $this->renderAjax('_document', [
            'model' => $model,//$this->findModel($id),
        ]);

Upvotes: 4

Blizz
Blizz

Reputation: 8408

You are looking for \yii\web\view::renderAjax() :) This does include javascript and css, but does not include the layout (and thus acts as a partial render).

Upvotes: 10

Related Questions