Score:1

Custom node routing

cz flag

I have a product content type with alias: /products/headphone. This product page has two url variations:

  • /products/headphone/wire
  • /products/headphone/wireless

Both urls should point to the same node, however within preprocess function or twig, I should be able to capture which variation is loaded (wire|wireless)

I figured I should create a custom module and handle custom routing:

my_module.routing.yml:

my_module.modality:
  path: '/products/{product_slug}/{variation}'
  defaults:
    _controller: '\Drupal\my_module\Controller\ProductController::action'
  requirements:
    _permission: 'access content'
  options:
    parameters:
      product_slug:
        type: string
      variation:
        type: string

The part I'm struggling with is how to point the controller back to preprocess function:

function my_module_preprocess_node__product_page(array &$variables){
  // some preprocess stuff
}

This is what I currently have in my controller:

\Drupal\my_module\Controller\ProductController:action

public function action($program_slug, $variation) 
{
return [
        'template' => 'node--program_page',
        'variation' => $variation
      ];
 }
4uk4 avatar
cn flag
This is not a good approach. You are trying to re-invent how Drupal is displaying entities. The quickest way is probably to remove the last part of the path in a path processor with a high priority and then let the normal Drupal routing let resolve the product node and render it, which then invokes the preprocess hook automatically. For the path processor I've described in a different question how to create the code with drush: https://drupal.stackexchange.com/a/307416/47547
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.