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>?

17

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

| improve this answer | |
  • 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 – Sunil Verma Nov 23 '16 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 ? – Sanjay Gohil Aug 21 '17 at 10:32
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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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