9

In magento 1.x, I can add the css files into the head using helper like below code.

<reference name="head">
    <action method="addCss"><stylesheet helper="module/helperclass/helperfunction"/></action>
</reference>

But cannot do this on Magento 2.

So now, I added this code <link rel="stylesheet" type="text/css" media="all" href="<?php echo $_helper->getCSSFile()?>"> into "after.body.start" container.

Anyone know how can I add custom template file into <head>?

2 Answers 2

19

If you want add css file into head you can use this code:

<head>
   <css src="path_to/file.css" />
</head>

But if you need to add custom block into head, you can use this code:

<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 class="Magento\Framework\View\Element\Template" name="block_name" template="path_to_file.phtml" />
        </referenceBlock>
    </body>
</page>

Hope this helps

3
  • 1
    Can you suggest how to do the same in admin, i have tried all reference block names but with no luck, though the output comes up correctly when i use content referenceblock Commented Nov 23, 2016 at 12:23
  • when i am using my custom block instead of Magento\Framework\View\Element\Template it is display error "object domdocument should be created" how to remove this error and use my custom block ? Commented Aug 21, 2017 at 10:32
  • that is not a custom block, it's the core Template block Commented Sep 7, 2023 at 10:18
2

Searched all over the web for this answer, finally got it through a lot of experimentation.

I believe this to be the easiest way:
Go to the page located in the Admin panel.
Find your page and scroll down past the content section to the layout update xml section.
In that box you can add page specific CSS and JS.

<head> <css src="js/ingredients.css> </head>  

This will add your script to the top of the head section.
(Making things tricky for your JS)

<head><script src="requirejs/require.js"/><script src="js/ingredients.js"/></head>  

Above you will notice that I added the requirejs file first. This is done because without adding it before your personalized JS file, you will not be able to access the other libraries loaded into requirejs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.