templatesdrupaltwigdrupal-8drupal-commerce

How to display store fields from the product template?


I have a Drupal 8.7 site and the Drupal Commerce 2.14 module

In the template of my store to display the field field_professionnel_cgv I use this code TWIG :

{{ store.field_professionnel_cgv }}

How to display this field from the template of my products.


Solution

  • You could add to your module mymodule_preprocess_commerce_product() hook function and inside that function get store entity and set twig variable with data from it so it will be available inside your template.

    Check how original function looks like at: /modules/contrib/commerce/modules/product/commerce_product.module

    function template_preprocess_commerce_product(array &$variables) {
      /** @var Drupal\commerce_product\Entity\ProductInterface $product */
      $product = $variables['elements']['#commerce_product'];
    
      $variables['product_entity'] = $product;
      $variables['product_url'] = $product->isNew() ? '' : $product->toUrl();
      $variables['product'] = [];
      foreach (Element::children($variables['elements']) as $key) {
        $variables['product'][$key] = $variables['elements'][$key];
      }
    }
    

    So you'll have to fetch store object and assign twig variable like it's done here.