Created
May 16, 2016 23:07
-
-
Save lvampa/e6ff35bd326a1cbc83a4581ef750be08 to your computer and use it in GitHub Desktop.
Magento 2 - Two ways to add files to page head
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Step-by-step guide | |
| Create the files | |
| Namespace/Module/view/frontend/web/hello.js | |
| Namespace/Module/view/frontend/web/test.js | |
| In the Layout | |
| NOTE - notice how the filename is the layout handle we want to use. | |
| Namespace/Module/view/frontend/view/layout/default_head_blocks.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="Namespace_Module::my-styles.css" /> | |
| <link src="Namespace_Module::hello.js" /> | |
| </head> | |
| </page> | |
| In a block | |
| NOTE - The head.additional block is called in the body node, but is rendered in the head after the rest of the head nodes are created. | |
| Namespace/Module/view/frontend/view/layout/default_head_blocks.xml | |
| <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> | |
| <body> | |
| <referenceBlock name="head.additional"> | |
| <block template="Namespace_Module::head.phtml" | |
| class="Namespace\Module\Block\Head" | |
| name="copious.test" /> | |
| </referenceBlock> | |
| </body> | |
| </page> | |
| Namespace/Module/Block/Head.php | |
| <?php | |
| namespace Namespace\Module\Block; | |
| class head extends \Magento\Framework\View\Element\Template | |
| { | |
| public $assetRepo; | |
| public function __construct( | |
| \Magento\Framework\View\Element\Template\Context $context, | |
| \Magento\Framework\View\Asset\Repository $repository, | |
| array $data = [] | |
| ){ | |
| $this->assetRepo = $repository; | |
| return parent::__construct($context, $data); | |
| } | |
| } | |
| Namespace/Module/view/templates/head.phtml | |
| <?php | |
| $assetRepo = $this->assetRepo; | |
| $asset = $assetRepo->createAsset('Namespace_Module::test.js'); | |
| $url = $asset->getUrl(); | |
| ?> | |
| <script src="<?php echo $url; ?>"></script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Namespace/Module/view/frontend/view/layout/default_head_blocks.xml - I think there is one too many view folders in here, should just be Namespace/Module/view/frontend/layout/default_head_blocks.xml no?