2

This question is specific to Magento 2.

I am attempting to inject additional stylesheets, Javascript and a template block into every page in a Magento 2 store. I have a functioning module which I have called additionalcontent. I am just unable to wrap my head around how to inject the block into the frontend.

In Magento 1 I would include additionalcontent.xml inside the theme layout with the following

<?xml version="1.0"?>
<layout version="0.1.0">
    <default>
    <reference name="head">
         <action method="addCss"><stylesheet>xzy/additionalstyles.css</stylesheet></action>
         <action method="addJs"><script>xzy/additionaljavascript.js</script></action>
    </reference>
    <reference name="after_body_start">
     <block type="core/template" before="-" as="additionaBlock" name="additionaBlock" template="xzy/additionalblock.phtml" />
    </reference>
</default>

</layout> 

Note, I am only attempting to inject a template block not generate a frontend URL/route.

Does anyone have an example of how to accomplish this in Magento 2?

8

First you should checkout the magento2 developer docs. There is also a whole bunch of technical resources located here: Can anyone suggest more technical resources for Magento 2?

Looking at a magento2 theme You should be able to accomplish this by doing the following.

All the layout xml files are now named via their handle so all the items in your default handle should live in default.xml. Because you are adding items to the head it should live in default_head_blocks.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="css/styles-m.css" />
        <css src="css/styles-l.css" media="screen and (min-width: 768px)"/>
        <css src="css/print.css" media="print" />
    </head>
</page>

Inside you can see the reference of <head>. Here You can see the child attributes that are allowed in those references.

As for adding a normal core block you should be able to do that by the following:

<block class="Magento\Framework\View\Element\Template" name="store.settings" group="navigation-sections" template="Magento_Theme::html/container.phtml">

see this example: https://github.com/magento/magento2/blob/develop/app/design/frontend/Magento/blank/Magento_Theme/layout/default.xml

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.