Magento – Magento 2 Theming – How are page layout and page configurations connected

layoutmagento2theme

I am creating a theme in Magento 2. So far I've figured out how to create a custom page layout for my homepage and how to style it with css. I'm moving on into adding JavaScript and more custom CSS, but I can't figure out how to do this for a specific page.

Every article and document I've come across mentions adding a script or link to the head using the defaults_head_blocks.xml or default.xml, which is great for something I need globally, but how would I add a script to the head of only one Page Layout?

For clarity and people new to this like me, this is my theme structure:

<theme_dir>/
  - Magento_Theme/
      - layout/
          - default_head_blocks.xml (as far as I can tell no use in my situation)
          - default.xml (nor this)

      - page_layout/
          - homepage.xml (my target page layout)

    layouts.xml (defines my Homepage layout)

Theres more to my theme, but these are the relevant files.

Is there specific naming convention or xml attribute (within default.xml) I can use if I want to configure homepage.xml? How would I configure my homepage.xml page layout?

EDIT
My question is about targeting a specific page layout, this is not a question about coding homepages specifically, it's just an example using my current situation. For example, if I make a custom 'About' page, how do I figure out what xml file to override? (keywords 'figure out')

Best Answer

First of all, we need to read: putting content in a custom homepage and Magento 2 Include js on the product page

So, we can add a custom js on home page only:

app/design/frontend/Vendor/Theme/Magento_Cms/layout/cms_index_index.xml

<?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">
    <head>
        <link src="js/mycustom.js"/>
         <!--<script src="Vendor_Module::js/extension.js"/>-->
    </head>
</page>

Or we can call a custom js in phtml:

<?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="content">
        <block class="Magento\Framework\View\Element\Template"
               name="custom.js" as="custom.js" template="Vendor_Module::custom/js.phtml"/>
       </referenceContainer>
    </body>
</page>

In your custom js:

require([
        'jquery'
    ], function ($) {
        console.log("Hello Homepage");
    });
Related Topic