In Magento 2, How to add Js and CSS using php in a page in frontend ? What are the php methods in magento 2 for adding css and js in a page object?
1 Answer
Method 1: Using Simple Layouts
In this method you can add the CSS/JS
files in frontend using layout files only.
1. Open the layout file present at: Webspeaks/Test/view/frontend/layout/default.xml
Adding layout in default.xml
will be available on almost all pages of your agento 2 site. You can also add this code to any particluar page using the following layout file:
Webspeaks/Test/view/frontend/layout/<frontName>_<controllerName>_<actionName>.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<css src="Webspeaks_Fancyfeedback/css/my_css.css"/>
<link src="Webspeaks_Fancyfeedback/js/my_js.js"/>
</head>
</page>
2 Now create the css and js files at following locations:
Webspeaks/Test/view/frontend/web/js/my_js.js
Webspeaks/Test/view/frontend/web/css/my_css.css
Now clear the cache using following command:
php bin/magento cache:clear
Method 2: Using Blocks
Now change the code of layout file as follows:
For this you can CSS/JS files by adding a block in the head block of Magento 2.
1.In your layout file add following code:
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<referenceBlock name="head.additional">
<block template="head.phtml"
class="Webspeaks\Fancyfeedback\Block\Head"
name="webspeaks_fancyfeedback_block_head" />
</referenceBlock>
</page>
Now create the Head.php
block class in your module: Webspeaks/Test/Block/Head.php
namespace Webspeaks\Fancyfeedback\Block;
class Head extends \Magento\Framework\View\Element\Template
{
public $assetRepository;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
array $data = [],
\Magento\Framework\View\Asset\Repository $assetRepository
)
{
// Get the asset repository to get URL of our assets
$this->assetRepository = $assetRepository;
return parent::__construct($context, $data);
}
}
You can see in step 1 we have specified the template file for our block. Now we will create the template file at: Webspeaks/Test/view/frontend/templates/head.phtml
<?php
$asset_repository = $this->assetRepository;
$js_asset = $asset_repository->createAsset('Webspeaks_Fancyfeedback/js/ws_ff.js');
$css_asset = $asset_repository->createAsset('Webspeaks_Fancyfeedback/css/ws_ff.css');
?>
<link href="<?php echo $css_asset->getUrl(); ?>" rel="stylesheet" type="text/css" />
<script src="<?php echo $js_asset->getUrl(); ?>"></script>
Again clear the cache and you are done.