0

Custom twig template is just this:

<ul id="rows">
  {% for product in products %}
    <li>{{ product.title }} <a href="{{ product.image }}">Image</a> {{ product.description }}</li>
  {% endfor %}
</ul>

My custom module sends an array of products, which are something like this

array(1) { [0]=> array(3) { ["title"]=> string(9) "Product 3" ["image"]=> string(56) "/sites/default/files/2019-11/128px-Small_Storage_Box.png" ["description"]=> string(22) "Description 3" } }

And I am sending it from a controller like this:

return array(
  '#title' => t('Return products list'),
  '#products' => $products,
  '#theme' => 'return-products',
);

In my .module file I've defined hook as:

<?php
function return_products_theme($existing, $type, $theme, $path) {
  return array(
    'products' => [
      'variables' => [],
    ]);
}

I know data is there in an array, it just doesn't go inside twig template. Even if I type some

Test it won't be shown.

6
  • 3
    Possible duplicate of How can I pass an array from a controller to a template?
    – leymannx
    Commented Nov 13, 2019 at 12:59
  • 1
    In your theme hook it must say 'variables' => ['products' => []],.
    – leymannx
    Commented Nov 13, 2019 at 13:00
  • @leymannx changing hook so it says 'variables' => ['products' => []], doesn't help. Still thanks.
    – user97041
    Commented Nov 13, 2019 at 13:11
  • @Budala1 In your template, prob needs to be {{ product['title'] }}
    – No Sssweat
    Commented Nov 13, 2019 at 13:13
  • 1
    Return Array should be '#theme' => 'products' since that's the current name of your template file in hook_theme(). But the answer below is probably what you were trying to do.
    – No Sssweat
    Commented Nov 13, 2019 at 13:26

1 Answer 1

3

Several things are wrong here.

Your hook_theme must return:

return [
  'return_products' => [
    'variables' => [
      'products' => NULL,
    ]
  ]
];

Now you have a template called return_products with a variable called products.

In your controller you must then use '#theme' => 'return_products', instead of '#theme' => 'return-products',.

Then create a template in mymodule/templates/return-products.html.twig.

Notice how your theme name must be with _(underscores) when referred to in PHP, but the file name must be with -(dashes).

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.