After being a long time observer I finally have a question that I can't find an answer to. I have tried searching, both on here and on Google, but to no avail.

I am using Drupal 8.3.2 with the Drupal Commerce 2 module.

I am trying to theme a product page. I have switched twig debugging and created my own 'commerce-product.html.twig' file to overwrite the default one.

The problem I am having is that I want to be able to insert the different fields in the html using the twig template engine like I have done for custom content types on some of the pages on my site.

<div class="header">
  <h5>{{ fields.field_header.content}}</h5>
<div class="body">
  {{ fields.body.content}}

For the example above, I created a view and a block, and within the block used the markup above to call the field values within the view.

Now that I have come to the product page I am unsure which is the correct way to proceed.

Should I create a view for a product page, or can I call the product values in a similar fashion to above. For example.

{{ product.field_product_image.content}}

Or do I need to create a view and select the fields I want to display etc. in a similar way to what I have done for my custom content types.

I have tried to search for the answer, but I haven't been able to find much help.

That's landed me here, making my first post.

  • I'm not actualy sure what you are asking but yes, if you want to display products, you are better off creating a view dedicated to do that – DarkBee May 26 '17 at 11:04

You should start off with copying the template from the Commerce module /modules/contrib/commerce/modules/product/templates/commerce-product.html.twig:

 * @file
 * Default product template.
 * Available variables:
 * - attributes: HTML attributes for the wrapper.
 * - product: The rendered product fields.
 *   Use 'product' to print them all, or print a subset such as
 *   'product.title'. Use the following code to exclude the
 *   printing of a given field:
 *   @code
 *   {{ product|without('title') }}
 *   @endcode
 * - product_entity: The product entity.
 * - product_url: The product URL.
 * @ingroup themeable
<article{{ attributes }}>
  {{- product|without('variation_attributes') -}}

You can then adjust the display according to your custom fields, so something like:

<article{{ attributes.addClass('product') }}>
  {{ product.field_header }}

  <div class="body">
      {{ product.body }}
  {{- product|without('field_header','body') -}}
  • could you explain a bit more. I am using default product, if I copy the existing template 'commerce-product.html.twig' what should I the new twig name be? How will it override the existing template? – Akhil Mohandas Nov 28 '19 at 18:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy