4

I tried to add a simple div into my Magento 2 theme. I've added this code to

/app/code/design/frontend/MyCompany/MyTheme/Magento_Theme/layout/default.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <body>
    <referenceContainer name="columns.top">
      <container name="topline" as="topline" htmlTag="div" htmlClass="topline" before="page.header">
        <block class="Magento\Framework\View\Element\Template" name="top.line" template="Magento_Theme::topline.phtml" />
      </container>
    </referenceContainer>
  </body>
</page>

And I added this file with some test content:

/app/code/design/frontend/MyCompany/MyTheme/Magento_Theme/templates/topline.phtml

Of course, I've tried other answers here in StackExchange, but nothing worked. I read that when there's no content, the dom even does not appear - is that correct? But main question: what's wrong with my code? Btw, mage cache cleared.

0

1 Answer 1

9

Change your default.xml to

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="header-wrapper">
            <block class="Magento\Framework\View\Element\Template" name="top.line" template="Magento_Theme::topline.phtml" />
        </referenceContainer>
    </body>
</page>

If you want to add your block to top header change <referenceContainer/> to

<referenceContainer name="header.panel">

Now flush cache and try.

6
  • Hi, thank you very much. I found a small but epc mistake in my "config": the directory was not templates but template... omg! Commented Aug 3, 2017 at 9:38
  • to add the block to the top of the header: add the before argument: <block ... before="-"> Commented Aug 3, 2017 at 9:49
  • Yes, you can also use before and after to repositioning blocks. Commented Aug 3, 2017 at 10:10
  • I'm using <move element="my_block" destination="header.container" before="-" /> to put a block at the very top position.
    – DevonDahon
    Commented Nov 6, 2017 at 3:49
  • 1
    Invalid template file: 'Magento_Theme::topline.phtml' in module: '' block's name: 'top.line'
    – Ashvini K
    Commented Aug 20, 2020 at 9:16

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.