How to Display Tabs with Attribute Values on Magento 2 Product Page

How to Display Tabs with Attribute Values on Magento 2 Product Page

While working on a new Magento 2 theme, one of our front end developers had a task to display the attribute value as a separate tab on the product page. This was something our team has never faced before, so we had to figure out the way to do it on the spot. In this article, we have decided to show you the solution we came up with while working on this issue.

The expected result looks like this:

image6

 

Attributes are attached to the Attribute Set and are filled for a product (click on the image to open it in full size):

image4

Our solution was to create a file catalog_product_view.xml in our own theme and a new template customattribute.phtml inside the theme to display the attribute value (of course it can be done using the module’s approach, but we have done it inside the theme).

Here is the location of the file (replace the red text with your own theme): design/frontend/BelVG/MyTheme/Magento_Catalog/layout/catalog_product_view.xml

The key points of this xml are:

  • <block class=”Magento\Catalog\Block\Product\View” name=”supplement_facts.tab” template=”Magento_Catalog::product/view/customattribute.phtml” group=”detailed_info”> where the name  should be unique; the template should contain the location of the template responsible for rendering the attribute content; the group should be equal to detailed_info;
  • <argument translate=”true” name=”title” xsi:type=”string”>Supplement Facts</argument> is the name of the tab; notice that the name of the argument is “title”;
  • <argument name=”code” xsi:type=”string”>supplement_facts</argument> is the name of the attribute; notice that the name of the argument is “code”.

Here is the location of the file (replace the red text with your own theme): design/frontend/BelVG/MyTheme/Magento_Catalog/templates/product/view/
customattribute.phtml

This is where we get the product data based on the attribute code.

Here is what we get as a result:

image3

 

This is how you display tabs with attribute values using the theme method. If something is still unclear, please leave your questions in the comment section below.



Post a new comment

top
BelVG Newsletter
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
Email *