Friday 11 November 2016

Yii2 include css file in view

It would be better to register your css and js files in an asset bundle, but you could also do:
$this->registerCss("body { background: #f00; }");
The code above will result in adding the following to the head section of the page:
<style>
body { background: #f00; }
</style>
$this->registerCssFile(Yii::$app->request->baseUrl.'/views/A_view/A.css');

$this->registerCssFile("http://example.com/css/themes/black-and-white.css", [
    'depends' => [BootstrapAsset::className()],
    'media' => 'print',
], 'css-print-theme');

The code above will add a link to CSS file to the head section of the page.
  • The first argument specifies the CSS file to be registered.
  • The second argument specifies the HTML attributes for the resulting <link> tag. The option depends is specially handled. It specifies which asset bundles this CSS file depends on. In this case, the dependent asset bundle is BootstrapAsset. This means the CSS file will be added after the CSS files in BootstrapAsset.
  • The last argument specifies an ID identifying this CSS file. If it is not provided, the URL of the CSS file will be used instead
It is highly recommended that you use asset bundles to register external CSS files rather than using registerCssFile(). Using asset bundles allows you to combine and compress multiple CSS files, which is desirable for high traffic websites.

No comments:

Post a Comment