Chapters Close

How To Use Private Content or Sections in Magento 2?

In this post, I will be guiding you on how to use private content or sections while developing e-commerce store on Magento 2

Since private content is specific to individual users, it’s reasonable to handle it on the client side i.e. web browser.

A section groups related pieces of customer data and uses a key to access and manage that data.

Magento loads sections by AJAX request to /customer/section/load/ and caches loaded data in the browser local storage under the key mage-cache-storage. Magento automatically tracks changes to a section and loads the updated section right away.

Here we will be using Aureatelabs as the Vendor name and CustomSection as the name of the module.  You can change this according to your Vendor and Module name.

Follow the below steps to define the custom section and use the data of the custom section in our custom phtml file.

Step 1: Define a custom section

We will define a custom section in the di.xml file by adding a new section into sections pool.

Create di.xml file in app/code/Aureatelabs/CustomSection/etc/frontend directory.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
	<type name="Magento\Customer\CustomerData\SectionPoolInterface">
    	<arguments>
        	<argument name="sectionSourceMap" xsi:type="array">
            	<item name="custom_section" xsi:type="string">Aureatelabs\CustomSection\CustomerData\CustomSection</item>
        	</argument>
    	</arguments>
	</type>
</config>

Next, create CustomSection.php file in app/code/Aureatelabs/CustomSection/CustomerData directory.

<?php
namespace Aureatelabs\CustomSection\CustomerData;
use Magento\Customer\CustomerData\SectionSourceInterface;

class CustomSection implements SectionSourceInterface
{
	public function getSectionData()
	{
    	return [
        	'customdata' => "We are getting data from custom section",
    	];
	}
}

In getSectionData() method we will define our data that we want to store in section.

Step 2: Display custom section data in frontend

We will display our custom section data in the product view page. You can get section data in any Magento pages.

Next, we will create catalog_product_view.xml in app/code/Aureatelabs/CustomSection/view/frontend/layout directory.

<?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="product.info.main">
        	<block class="Magento\Catalog\Block\Product\View" name="aureatelabs_custom_section" after="-" template="Aureatelabs_CustomSection::custom_section.phtml" />
    	</referenceContainer>
	</body>
</page>

Next, we will create a custom_section.phtml in app/code/Aureatelabs/CustomSection/view/frontend/templates directory.

<div class="aureatelabs-custom-section"data-bind="scope: 'section'">
	<p data-bind="text: customsection().customdata"></p>
</div>
<script type="text/x-magento-init">
	{
    	"*": {
        	"Magento_Ui/js/core/app": {
            	"components": {
                	"section": {
                    	"component": "Aureatelabs_CustomSection/js/section"
                	}
            	}
        	}
    	}
	}
</script>

Next, We will create section.js in app/code/Aureatelabs/CustomSection/view/frontend/web/js directory.

define([
	'uiComponent',
	'Magento_Customer/js/customer-data'
], function (Component, customerData) {
	'use strict';

	return Component.extend({
    	initialize: function () {
        	this._super();
        	this.customsection = customerData.get('custom_section');
    	}
	});
});

Now run the below command and check on any product view page.

php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:flush

You can see the custom section data in the product view page.

Verify custom section is loaded or not by running below url

{store_url}/customer/section/load/?sections=custom_section

See custom section data in browser local storage.

In the section.js file, we have used Magento_Customer/js/customer-data as this Magento js library file is responsible for set section data and get section data. Section data gets updated when ajax call with the post, put, delete requests are made.

Additional Information

When caching is enabled, the system first stores the entire page content. Then, it uses sections to dynamically manage and update the page components.

For example, when the system caches the entire page, it doesn’t reload everything after a customer logs in or logs out. Instead, the sections update only the components, such as the customer name, cart, and wishlist, with the latest values.

The system fetches all section data in a single AJAX call, significantly reducing the number of AJAX requests.

Magento treats section data as changed when the customer sends a state modification request (POST, PUT, or DELETE). To minimize the load on the server, developers should specify which action (or request) updates which customer data section in etc/frontend/sections.xml.

You can refer Magento/Catalog/etc/frontend/sections.xml file.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
	<action name="catalog/product_compare/add">
    	<section name="compare-products"/>
	</action>
	<action name="catalog/product_compare/remove">
    	<section name="compare-products"/>
	</action>
	<action name="catalog/product_compare/clear">
    	<section name="compare-products"/>
	</action>
	<action name="customer/account/logout">
    	<section name="recently_viewed_product"/>
    	<section name="recently_compared_product"/>
	</action>
</config>

In the section.xml file, they have defined update the compare-products section when one of these actions catalog/product_compare/addcatalog/product_compare/remove, catalog/product_compare/clear are requested.

If the action name is, Magento updates that section on every POST and PUT request. If the section tag is missing, Magento updates all sections.

You can refer Magento/Theme/etc/frontend/sections.xml file.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="*">
        <section name="messages"/>
    </action>
</config>

In the section.xml file, they have defined update the messages section on each POST and PUT request.

If you want to reload your sections in Magento 2 data when the page refreshes, you must reload your custom section data in your JS file.

define([
	'uiComponent',
	'Magento_Customer/js/customer-data'
], function (Component, customerData) {
	'use strict';

	return Component.extend({
    	initialize: function () {
        	this._super();
        	customerData.reload('custom_section');
        	this.customsection = customerData.get('custom_section');
    	}
	});
});

Here we have added customerData.reload('custom_section'); to reload section data whenever we refresh the page.

FAQs

What is private content in Magento 2?


Private content in Magento 2 is data accessible only to a particular user, based on the configurational changes made by them. This can be anything from purchase history to payment information. The customer-data.js library in Magento 2 checks whether a customer is logged in. Then, instead of refreshing the entire page cache, it efficiently sends server requests to reload only specific parts of the data.

How do I override layout XML in Magento 2?


To override layout XML in Magento 2, create a folder structure with the same name in themes as present in view/frontend. Then, change the etc/module.xml file and replace it by the new file created. You can do this by placing the file in app/design/frontend/[Vendor]/[Theme_Name]/Vendor_ModuleName/layout/some_layout.xml

Where is config xml in Magento?


The config.xml in Magento is located in the DOMAIN_HOME/config directory. The servers get their configuration data from these files. Each server has its own configuration file in the domain which can be accessed through <module_folder>/etc/adminhtml/system.xml. The config.xml files are used to set specific values for the configuration of the system.

How to use the section XML in Magento 2?


To use section XML in Magento 2, create a new layout XML file in the app/code/[VendorName]/[ModuleName]/view/frontend/layout directory. Then, refresh the cache and open any product page to view the section data.
Sections in Magento 2 define the layout configuration for different store areas, such as the header, footer, and content.

Related resources:

Speak your Mind

Post a Comment

Got a question? Have a feedback? Please feel free to leave your ideas, opinions, and questions in the comments section of our post! ❤️

* This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Thank you for your feedback

Comments (1)

  1. customerData.reload(‘custom_section’);
    should be
    customerData.reload([‘custom_section’]);

    Reply

Grow your online business like 4,913 subscribers

    * This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
    envelope

    Thank You!

    We are reviewing your submission, and will be in touch shortly.