Skip to content

Instantly share code, notes, and snippets.

@lvampa
Created May 16, 2016 23:07
Show Gist options
  • Select an option

  • Save lvampa/e6ff35bd326a1cbc83a4581ef750be08 to your computer and use it in GitHub Desktop.

Select an option

Save lvampa/e6ff35bd326a1cbc83a4581ef750be08 to your computer and use it in GitHub Desktop.
Magento 2 - Two ways to add files to page head
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>
@domani-smatysik
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment