How to do a redirect in node.html.twig?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP

up vote
1
down vote

favorite

1

I’m trying to do a redirect on my node.html.twig template based on the content type because I’m using views for my content.

I tried this:

{% do redirect('/example') %}

or this:

{% redirect '/example' %}

but nothing works. Any idea?

share|improve this question

  • 1

    You shouldn’t (and hopefully can’t) perform a redirect in the template layer. This needs to be done much further up the chain
    – Clive
    Nov 29 at 15:08

  • Did you try just having a Views path set to node/%nid to overtake content?
    – Kevin
    Nov 29 at 15:11

up vote
1
down vote

favorite

1

I’m trying to do a redirect on my node.html.twig template based on the content type because I’m using views for my content.

I tried this:

{% do redirect('/example') %}

or this:

{% redirect '/example' %}

but nothing works. Any idea?

share|improve this question

  • 1

    You shouldn’t (and hopefully can’t) perform a redirect in the template layer. This needs to be done much further up the chain
    – Clive
    Nov 29 at 15:08

  • Did you try just having a Views path set to node/%nid to overtake content?
    – Kevin
    Nov 29 at 15:11

up vote
1
down vote

favorite

1

up vote
1
down vote

favorite

1
1

I’m trying to do a redirect on my node.html.twig template based on the content type because I’m using views for my content.

I tried this:

{% do redirect('/example') %}

or this:

{% redirect '/example' %}

but nothing works. Any idea?

share|improve this question

I’m trying to do a redirect on my node.html.twig template based on the content type because I’m using views for my content.

I tried this:

{% do redirect('/example') %}

or this:

{% redirect '/example' %}

but nothing works. Any idea?

8 redirect

share|improve this question

share|improve this question

share|improve this question

share|improve this question

edited Nov 29 at 18:48

Pierre.Vriens

35.2k1335155

35.2k1335155

asked Nov 29 at 15:04

Mauricio

133

133

  • 1

    You shouldn’t (and hopefully can’t) perform a redirect in the template layer. This needs to be done much further up the chain
    – Clive
    Nov 29 at 15:08

  • Did you try just having a Views path set to node/%nid to overtake content?
    – Kevin
    Nov 29 at 15:11

  • 1

    You shouldn’t (and hopefully can’t) perform a redirect in the template layer. This needs to be done much further up the chain
    – Clive
    Nov 29 at 15:08

  • Did you try just having a Views path set to node/%nid to overtake content?
    – Kevin
    Nov 29 at 15:11

1

1

You shouldn’t (and hopefully can’t) perform a redirect in the template layer. This needs to be done much further up the chain
– Clive
Nov 29 at 15:08

You shouldn’t (and hopefully can’t) perform a redirect in the template layer. This needs to be done much further up the chain
– Clive
Nov 29 at 15:08

Did you try just having a Views path set to node/%nid to overtake content?
– Kevin
Nov 29 at 15:11

Did you try just having a Views path set to node/%nid to overtake content?
– Kevin
Nov 29 at 15:11

3 Answers
3

active

oldest

votes

up vote
4
down vote

accepted

Don’t do it in the Twig file. This is not where that logic belongs. It should be in an Event.

See this similar question: EventSubscriber called on specific node type or path

All that is left is checking the node type and sending a RedirectResponse.

Gabe Sullice has a Gist that sounds very close to what you are trying to accomplish: https://gist.github.com/gabesullice/96bdae1518d11bb4565e72c33ffcae4c

So your code would fill in something like:

  /**
   * Determines whether we should send a RedirectResponse for this node.
   */
  protected function redirectApplies(NodeInterface $node) : bool {
    $redirect_types = ['type_1', 'type_2', 'type_3'];
    return in_array($node->getType(), $redirect_types);
  }

But if you go to different urls for different types, you will need to adjust it a little more.

share|improve this answer

  • Yes, the logic belongs either in the controller or in an event subscriber. Instead of the response event (as in the linked Gist) a faster option would be the request event, see this change record drupal.org/node/2013014.
    – 4k4
    Nov 29 at 16:53

  • This method works perfectly, i used and modified a few this code and works finally @kevin
    – Mauricio
    Nov 29 at 17:22

up vote
0
down vote

Where did you see the redirect functionality? I dont think it’s part of standard twig or anything drupal provides: https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates

You’d be better of doing the redirect in a proprocess function maybe. This might help
Redirect basic page to external url when visiting page

share|improve this answer

  • It looks like its a function in CraftCMS but not in Twig itself. docs.craftcms.com/v2/templating/redirect.html
    – Kevin
    Nov 29 at 15:18

  • (that is to say, they must have created a custom Twig function and it shows up in google results – it also appears in BranchCMS).
    – Kevin
    Nov 29 at 15:27

up vote
0
down vote

As @Kevin suggested
i created a custom module based on Gabe Sullice code:
https://gist.github.com/gabesullice/96bdae1518d11bb4565e72c33ffcae4c

My final code redirect to custom url by content type:

    namespace Drupalredirect_node_moduleEventSubscriber;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
use SymfonyComponentEventDispatcherEvent;
use DrupalCoreRoutingCurrentRouteMatch;
use DrupalnodeNodeInterface;
use DrupalCoreCacheCacheableRedirectResponse;
use SymfonyComponentHttpFoundationRedirectResponse;
/**
 * Class ResponseSubscriber.
 *
 * @package Drupalredirect_node_module
 */
class ResponseSubscriber implements EventSubscriberInterface {
  /**
   * DrupalCoreRoutingCurrentRouteMatch definition.
   *
   * @var DrupalCoreRoutingCurrentRouteMatch
   */
  protected $routeMatch;
  /**
   * Constructor.
   */
  public function __construct(CurrentRouteMatch $current_route_match) {
    $this->routeMatch = $current_route_match;
  }
  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events['kernel.response'] = ['handle'];
    return $events;
  }
  /**
   * This method is called whenever the kernel.response event is
   * dispatched.
   *
   * @param GetResponseEvent $event
   */
  public function handle(Event $event) {
    $route_name = $this->routeMatch->getRouteName();
    switch ($route_name) {
      case 'entity.node.canonical':
        $node = $this->routeMatch->getParameter('node');
        if ($this->redirectApplies($node)) {
          $event->setResponse(new RedirectResponse($this->getRedirect($node)));
        }
    }
  }
  /**
   * Determines whether we should send a RedirectResponse for this node.
   */
   protected function redirectApplies(NodeInterface $node) {
    // One should have logic here returning TRUE or FALSE for whether we should redirect this response.
    $redirect_on = ['programas', 'servicios', 'aliados', 'testimonios', 'nosotros', 'nuestro_equipo', 'datos_de_contacto', 'banner', 'seccion'];
    return (in_array($node->getType(), $redirect_on));

  }
  protected function getRedirect(NodeInterface $node) {
    // We can cache this response when this is fixed: https://www.drupal.org/node/2573807
    // $response = CacheableRedirectResponse::create($url);
    // $response->addCacheableDependency($node);
    // return $response;

    switch ($node->getType()) {
      case 'nuestro_equipo':
        $url = "/profesionales";
        break;

      case 'datos_de_contacto':
        $url = "/contacto";
        break;

      case 'nosotros':
        $url = "/nosotros";
        break; 

      case 'banner':
        $url = "/";
        break;  

      case 'testimonios':
        $url = "/testimonios";
        break;

      case 'aliados':
        $url = "/aliados";
        break;

      default:
        $search_chars = array('á','é','í','ó','ú','ñ','Á','É','Í','Ó','Ú','Ñ',' ');
        $replace_chars= array('a','e','i','o','u','n','a','e','i','o','u','n','-');
        $node_title = str_replace($search_chars, $replace_chars, strtolower( $node->getTitle() ));
        $url = "/".$node->getType()."/".$node_title;
        break;
    }
    return $url;
  }
}

share|improve this answer

    Your Answer

    StackExchange.ready(function() {
    var channelOptions = {
    tags: “”.split(” “),
    id: “220”
    };
    initTagRenderer(“”.split(” “), “”.split(” “), channelOptions);

    StackExchange.using(“externalEditor”, function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using(“snippets”, function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: ‘answer’,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: “”,
    imageUploader: {
    brandingHtml: “Powered by u003ca class=”icon-imgur-white” href=”https://imgur.com/”u003eu003c/au003e”,
    contentPolicyHtml: “User contributions licensed under u003ca href=”https://creativecommons.org/licenses/by-sa/3.0/”u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href=”https://stackoverflow.com/legal/content-policy”u003e(content policy)u003c/au003e”,
    allowUrls: true
    },
    onDemand: true,
    discardSelector: “.discard-answer”
    ,immediatelyShowMarkdownHelp:true
    });

    }
    });

    draft saved
    draft discarded

    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin(‘.new-post-login’, ‘https%3a%2f%2fdrupal.stackexchange.com%2fquestions%2f273233%2fhow-to-do-a-redirect-in-node-html-twig%23new-answer’, ‘question_page’);
    }
    );

    Post as a guest

    Required, but never shown

    3 Answers
    3

    active

    oldest

    votes

    3 Answers
    3

    active

    oldest

    votes

    active

    oldest

    votes

    active

    oldest

    votes

    up vote
    4
    down vote

    accepted

    Don’t do it in the Twig file. This is not where that logic belongs. It should be in an Event.

    See this similar question: EventSubscriber called on specific node type or path

    All that is left is checking the node type and sending a RedirectResponse.

    Gabe Sullice has a Gist that sounds very close to what you are trying to accomplish: https://gist.github.com/gabesullice/96bdae1518d11bb4565e72c33ffcae4c

    So your code would fill in something like:

      /**
       * Determines whether we should send a RedirectResponse for this node.
       */
      protected function redirectApplies(NodeInterface $node) : bool {
        $redirect_types = ['type_1', 'type_2', 'type_3'];
        return in_array($node->getType(), $redirect_types);
      }
    

    But if you go to different urls for different types, you will need to adjust it a little more.

    share|improve this answer

    • Yes, the logic belongs either in the controller or in an event subscriber. Instead of the response event (as in the linked Gist) a faster option would be the request event, see this change record drupal.org/node/2013014.
      – 4k4
      Nov 29 at 16:53

    • This method works perfectly, i used and modified a few this code and works finally @kevin
      – Mauricio
      Nov 29 at 17:22

    up vote
    4
    down vote

    accepted

    Don’t do it in the Twig file. This is not where that logic belongs. It should be in an Event.

    See this similar question: EventSubscriber called on specific node type or path

    All that is left is checking the node type and sending a RedirectResponse.

    Gabe Sullice has a Gist that sounds very close to what you are trying to accomplish: https://gist.github.com/gabesullice/96bdae1518d11bb4565e72c33ffcae4c

    So your code would fill in something like:

      /**
       * Determines whether we should send a RedirectResponse for this node.
       */
      protected function redirectApplies(NodeInterface $node) : bool {
        $redirect_types = ['type_1', 'type_2', 'type_3'];
        return in_array($node->getType(), $redirect_types);
      }
    

    But if you go to different urls for different types, you will need to adjust it a little more.

    share|improve this answer

    • Yes, the logic belongs either in the controller or in an event subscriber. Instead of the response event (as in the linked Gist) a faster option would be the request event, see this change record drupal.org/node/2013014.
      – 4k4
      Nov 29 at 16:53

    • This method works perfectly, i used and modified a few this code and works finally @kevin
      – Mauricio
      Nov 29 at 17:22

    up vote
    4
    down vote

    accepted

    up vote
    4
    down vote

    accepted

    Don’t do it in the Twig file. This is not where that logic belongs. It should be in an Event.

    See this similar question: EventSubscriber called on specific node type or path

    All that is left is checking the node type and sending a RedirectResponse.

    Gabe Sullice has a Gist that sounds very close to what you are trying to accomplish: https://gist.github.com/gabesullice/96bdae1518d11bb4565e72c33ffcae4c

    So your code would fill in something like:

      /**
       * Determines whether we should send a RedirectResponse for this node.
       */
      protected function redirectApplies(NodeInterface $node) : bool {
        $redirect_types = ['type_1', 'type_2', 'type_3'];
        return in_array($node->getType(), $redirect_types);
      }
    

    But if you go to different urls for different types, you will need to adjust it a little more.

    share|improve this answer

    Don’t do it in the Twig file. This is not where that logic belongs. It should be in an Event.

    See this similar question: EventSubscriber called on specific node type or path

    All that is left is checking the node type and sending a RedirectResponse.

    Gabe Sullice has a Gist that sounds very close to what you are trying to accomplish: https://gist.github.com/gabesullice/96bdae1518d11bb4565e72c33ffcae4c

    So your code would fill in something like:

      /**
       * Determines whether we should send a RedirectResponse for this node.
       */
      protected function redirectApplies(NodeInterface $node) : bool {
        $redirect_types = ['type_1', 'type_2', 'type_3'];
        return in_array($node->getType(), $redirect_types);
      }
    

    But if you go to different urls for different types, you will need to adjust it a little more.

    share|improve this answer

    share|improve this answer

    share|improve this answer

    edited Nov 29 at 15:52

    answered Nov 29 at 15:08

    Kevin

    17k848106

    17k848106

    • Yes, the logic belongs either in the controller or in an event subscriber. Instead of the response event (as in the linked Gist) a faster option would be the request event, see this change record drupal.org/node/2013014.
      – 4k4
      Nov 29 at 16:53

    • This method works perfectly, i used and modified a few this code and works finally @kevin
      – Mauricio
      Nov 29 at 17:22

    • Yes, the logic belongs either in the controller or in an event subscriber. Instead of the response event (as in the linked Gist) a faster option would be the request event, see this change record drupal.org/node/2013014.
      – 4k4
      Nov 29 at 16:53

    • This method works perfectly, i used and modified a few this code and works finally @kevin
      – Mauricio
      Nov 29 at 17:22

    Yes, the logic belongs either in the controller or in an event subscriber. Instead of the response event (as in the linked Gist) a faster option would be the request event, see this change record drupal.org/node/2013014.
    – 4k4
    Nov 29 at 16:53

    Yes, the logic belongs either in the controller or in an event subscriber. Instead of the response event (as in the linked Gist) a faster option would be the request event, see this change record drupal.org/node/2013014.
    – 4k4
    Nov 29 at 16:53

    This method works perfectly, i used and modified a few this code and works finally @kevin
    – Mauricio
    Nov 29 at 17:22

    This method works perfectly, i used and modified a few this code and works finally @kevin
    – Mauricio
    Nov 29 at 17:22

    up vote
    0
    down vote

    Where did you see the redirect functionality? I dont think it’s part of standard twig or anything drupal provides: https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates

    You’d be better of doing the redirect in a proprocess function maybe. This might help
    Redirect basic page to external url when visiting page

    share|improve this answer

    • It looks like its a function in CraftCMS but not in Twig itself. docs.craftcms.com/v2/templating/redirect.html
      – Kevin
      Nov 29 at 15:18

    • (that is to say, they must have created a custom Twig function and it shows up in google results – it also appears in BranchCMS).
      – Kevin
      Nov 29 at 15:27

    up vote
    0
    down vote

    Where did you see the redirect functionality? I dont think it’s part of standard twig or anything drupal provides: https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates

    You’d be better of doing the redirect in a proprocess function maybe. This might help
    Redirect basic page to external url when visiting page

    share|improve this answer

    • It looks like its a function in CraftCMS but not in Twig itself. docs.craftcms.com/v2/templating/redirect.html
      – Kevin
      Nov 29 at 15:18

    • (that is to say, they must have created a custom Twig function and it shows up in google results – it also appears in BranchCMS).
      – Kevin
      Nov 29 at 15:27

    up vote
    0
    down vote

    up vote
    0
    down vote

    Where did you see the redirect functionality? I dont think it’s part of standard twig or anything drupal provides: https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates

    You’d be better of doing the redirect in a proprocess function maybe. This might help
    Redirect basic page to external url when visiting page

    share|improve this answer

    Where did you see the redirect functionality? I dont think it’s part of standard twig or anything drupal provides: https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates

    You’d be better of doing the redirect in a proprocess function maybe. This might help
    Redirect basic page to external url when visiting page

    share|improve this answer

    share|improve this answer

    share|improve this answer

    answered Nov 29 at 15:08

    Leigh Mason

    1,36146

    1,36146

    • It looks like its a function in CraftCMS but not in Twig itself. docs.craftcms.com/v2/templating/redirect.html
      – Kevin
      Nov 29 at 15:18

    • (that is to say, they must have created a custom Twig function and it shows up in google results – it also appears in BranchCMS).
      – Kevin
      Nov 29 at 15:27

    • It looks like its a function in CraftCMS but not in Twig itself. docs.craftcms.com/v2/templating/redirect.html
      – Kevin
      Nov 29 at 15:18

    • (that is to say, they must have created a custom Twig function and it shows up in google results – it also appears in BranchCMS).
      – Kevin
      Nov 29 at 15:27

    It looks like its a function in CraftCMS but not in Twig itself. docs.craftcms.com/v2/templating/redirect.html
    – Kevin
    Nov 29 at 15:18

    It looks like its a function in CraftCMS but not in Twig itself. docs.craftcms.com/v2/templating/redirect.html
    – Kevin
    Nov 29 at 15:18

    (that is to say, they must have created a custom Twig function and it shows up in google results – it also appears in BranchCMS).
    – Kevin
    Nov 29 at 15:27

    (that is to say, they must have created a custom Twig function and it shows up in google results – it also appears in BranchCMS).
    – Kevin
    Nov 29 at 15:27

    up vote
    0
    down vote

    As @Kevin suggested
    i created a custom module based on Gabe Sullice code:
    https://gist.github.com/gabesullice/96bdae1518d11bb4565e72c33ffcae4c

    My final code redirect to custom url by content type:

        namespace Drupalredirect_node_moduleEventSubscriber;
    use SymfonyComponentEventDispatcherEventSubscriberInterface;
    use SymfonyComponentEventDispatcherEvent;
    use DrupalCoreRoutingCurrentRouteMatch;
    use DrupalnodeNodeInterface;
    use DrupalCoreCacheCacheableRedirectResponse;
    use SymfonyComponentHttpFoundationRedirectResponse;
    /**
     * Class ResponseSubscriber.
     *
     * @package Drupalredirect_node_module
     */
    class ResponseSubscriber implements EventSubscriberInterface {
      /**
       * DrupalCoreRoutingCurrentRouteMatch definition.
       *
       * @var DrupalCoreRoutingCurrentRouteMatch
       */
      protected $routeMatch;
      /**
       * Constructor.
       */
      public function __construct(CurrentRouteMatch $current_route_match) {
        $this->routeMatch = $current_route_match;
      }
      /**
       * {@inheritdoc}
       */
      static function getSubscribedEvents() {
        $events['kernel.response'] = ['handle'];
        return $events;
      }
      /**
       * This method is called whenever the kernel.response event is
       * dispatched.
       *
       * @param GetResponseEvent $event
       */
      public function handle(Event $event) {
        $route_name = $this->routeMatch->getRouteName();
        switch ($route_name) {
          case 'entity.node.canonical':
            $node = $this->routeMatch->getParameter('node');
            if ($this->redirectApplies($node)) {
              $event->setResponse(new RedirectResponse($this->getRedirect($node)));
            }
        }
      }
      /**
       * Determines whether we should send a RedirectResponse for this node.
       */
       protected function redirectApplies(NodeInterface $node) {
        // One should have logic here returning TRUE or FALSE for whether we should redirect this response.
        $redirect_on = ['programas', 'servicios', 'aliados', 'testimonios', 'nosotros', 'nuestro_equipo', 'datos_de_contacto', 'banner', 'seccion'];
        return (in_array($node->getType(), $redirect_on));
    
      }
      protected function getRedirect(NodeInterface $node) {
        // We can cache this response when this is fixed: https://www.drupal.org/node/2573807
        // $response = CacheableRedirectResponse::create($url);
        // $response->addCacheableDependency($node);
        // return $response;
    
        switch ($node->getType()) {
          case 'nuestro_equipo':
            $url = "/profesionales";
            break;
    
          case 'datos_de_contacto':
            $url = "/contacto";
            break;
    
          case 'nosotros':
            $url = "/nosotros";
            break; 
    
          case 'banner':
            $url = "/";
            break;  
    
          case 'testimonios':
            $url = "/testimonios";
            break;
    
          case 'aliados':
            $url = "/aliados";
            break;
    
          default:
            $search_chars = array('á','é','í','ó','ú','ñ','Á','É','Í','Ó','Ú','Ñ',' ');
            $replace_chars= array('a','e','i','o','u','n','a','e','i','o','u','n','-');
            $node_title = str_replace($search_chars, $replace_chars, strtolower( $node->getTitle() ));
            $url = "/".$node->getType()."/".$node_title;
            break;
        }
        return $url;
      }
    }
    

    share|improve this answer

      up vote
      0
      down vote

      As @Kevin suggested
      i created a custom module based on Gabe Sullice code:
      https://gist.github.com/gabesullice/96bdae1518d11bb4565e72c33ffcae4c

      My final code redirect to custom url by content type:

          namespace Drupalredirect_node_moduleEventSubscriber;
      use SymfonyComponentEventDispatcherEventSubscriberInterface;
      use SymfonyComponentEventDispatcherEvent;
      use DrupalCoreRoutingCurrentRouteMatch;
      use DrupalnodeNodeInterface;
      use DrupalCoreCacheCacheableRedirectResponse;
      use SymfonyComponentHttpFoundationRedirectResponse;
      /**
       * Class ResponseSubscriber.
       *
       * @package Drupalredirect_node_module
       */
      class ResponseSubscriber implements EventSubscriberInterface {
        /**
         * DrupalCoreRoutingCurrentRouteMatch definition.
         *
         * @var DrupalCoreRoutingCurrentRouteMatch
         */
        protected $routeMatch;
        /**
         * Constructor.
         */
        public function __construct(CurrentRouteMatch $current_route_match) {
          $this->routeMatch = $current_route_match;
        }
        /**
         * {@inheritdoc}
         */
        static function getSubscribedEvents() {
          $events['kernel.response'] = ['handle'];
          return $events;
        }
        /**
         * This method is called whenever the kernel.response event is
         * dispatched.
         *
         * @param GetResponseEvent $event
         */
        public function handle(Event $event) {
          $route_name = $this->routeMatch->getRouteName();
          switch ($route_name) {
            case 'entity.node.canonical':
              $node = $this->routeMatch->getParameter('node');
              if ($this->redirectApplies($node)) {
                $event->setResponse(new RedirectResponse($this->getRedirect($node)));
              }
          }
        }
        /**
         * Determines whether we should send a RedirectResponse for this node.
         */
         protected function redirectApplies(NodeInterface $node) {
          // One should have logic here returning TRUE or FALSE for whether we should redirect this response.
          $redirect_on = ['programas', 'servicios', 'aliados', 'testimonios', 'nosotros', 'nuestro_equipo', 'datos_de_contacto', 'banner', 'seccion'];
          return (in_array($node->getType(), $redirect_on));
      
        }
        protected function getRedirect(NodeInterface $node) {
          // We can cache this response when this is fixed: https://www.drupal.org/node/2573807
          // $response = CacheableRedirectResponse::create($url);
          // $response->addCacheableDependency($node);
          // return $response;
      
          switch ($node->getType()) {
            case 'nuestro_equipo':
              $url = "/profesionales";
              break;
      
            case 'datos_de_contacto':
              $url = "/contacto";
              break;
      
            case 'nosotros':
              $url = "/nosotros";
              break; 
      
            case 'banner':
              $url = "/";
              break;  
      
            case 'testimonios':
              $url = "/testimonios";
              break;
      
            case 'aliados':
              $url = "/aliados";
              break;
      
            default:
              $search_chars = array('á','é','í','ó','ú','ñ','Á','É','Í','Ó','Ú','Ñ',' ');
              $replace_chars= array('a','e','i','o','u','n','a','e','i','o','u','n','-');
              $node_title = str_replace($search_chars, $replace_chars, strtolower( $node->getTitle() ));
              $url = "/".$node->getType()."/".$node_title;
              break;
          }
          return $url;
        }
      }
      

      share|improve this answer

        up vote
        0
        down vote

        up vote
        0
        down vote

        As @Kevin suggested
        i created a custom module based on Gabe Sullice code:
        https://gist.github.com/gabesullice/96bdae1518d11bb4565e72c33ffcae4c

        My final code redirect to custom url by content type:

            namespace Drupalredirect_node_moduleEventSubscriber;
        use SymfonyComponentEventDispatcherEventSubscriberInterface;
        use SymfonyComponentEventDispatcherEvent;
        use DrupalCoreRoutingCurrentRouteMatch;
        use DrupalnodeNodeInterface;
        use DrupalCoreCacheCacheableRedirectResponse;
        use SymfonyComponentHttpFoundationRedirectResponse;
        /**
         * Class ResponseSubscriber.
         *
         * @package Drupalredirect_node_module
         */
        class ResponseSubscriber implements EventSubscriberInterface {
          /**
           * DrupalCoreRoutingCurrentRouteMatch definition.
           *
           * @var DrupalCoreRoutingCurrentRouteMatch
           */
          protected $routeMatch;
          /**
           * Constructor.
           */
          public function __construct(CurrentRouteMatch $current_route_match) {
            $this->routeMatch = $current_route_match;
          }
          /**
           * {@inheritdoc}
           */
          static function getSubscribedEvents() {
            $events['kernel.response'] = ['handle'];
            return $events;
          }
          /**
           * This method is called whenever the kernel.response event is
           * dispatched.
           *
           * @param GetResponseEvent $event
           */
          public function handle(Event $event) {
            $route_name = $this->routeMatch->getRouteName();
            switch ($route_name) {
              case 'entity.node.canonical':
                $node = $this->routeMatch->getParameter('node');
                if ($this->redirectApplies($node)) {
                  $event->setResponse(new RedirectResponse($this->getRedirect($node)));
                }
            }
          }
          /**
           * Determines whether we should send a RedirectResponse for this node.
           */
           protected function redirectApplies(NodeInterface $node) {
            // One should have logic here returning TRUE or FALSE for whether we should redirect this response.
            $redirect_on = ['programas', 'servicios', 'aliados', 'testimonios', 'nosotros', 'nuestro_equipo', 'datos_de_contacto', 'banner', 'seccion'];
            return (in_array($node->getType(), $redirect_on));
        
          }
          protected function getRedirect(NodeInterface $node) {
            // We can cache this response when this is fixed: https://www.drupal.org/node/2573807
            // $response = CacheableRedirectResponse::create($url);
            // $response->addCacheableDependency($node);
            // return $response;
        
            switch ($node->getType()) {
              case 'nuestro_equipo':
                $url = "/profesionales";
                break;
        
              case 'datos_de_contacto':
                $url = "/contacto";
                break;
        
              case 'nosotros':
                $url = "/nosotros";
                break; 
        
              case 'banner':
                $url = "/";
                break;  
        
              case 'testimonios':
                $url = "/testimonios";
                break;
        
              case 'aliados':
                $url = "/aliados";
                break;
        
              default:
                $search_chars = array('á','é','í','ó','ú','ñ','Á','É','Í','Ó','Ú','Ñ',' ');
                $replace_chars= array('a','e','i','o','u','n','a','e','i','o','u','n','-');
                $node_title = str_replace($search_chars, $replace_chars, strtolower( $node->getTitle() ));
                $url = "/".$node->getType()."/".$node_title;
                break;
            }
            return $url;
          }
        }
        

        share|improve this answer

        As @Kevin suggested
        i created a custom module based on Gabe Sullice code:
        https://gist.github.com/gabesullice/96bdae1518d11bb4565e72c33ffcae4c

        My final code redirect to custom url by content type:

            namespace Drupalredirect_node_moduleEventSubscriber;
        use SymfonyComponentEventDispatcherEventSubscriberInterface;
        use SymfonyComponentEventDispatcherEvent;
        use DrupalCoreRoutingCurrentRouteMatch;
        use DrupalnodeNodeInterface;
        use DrupalCoreCacheCacheableRedirectResponse;
        use SymfonyComponentHttpFoundationRedirectResponse;
        /**
         * Class ResponseSubscriber.
         *
         * @package Drupalredirect_node_module
         */
        class ResponseSubscriber implements EventSubscriberInterface {
          /**
           * DrupalCoreRoutingCurrentRouteMatch definition.
           *
           * @var DrupalCoreRoutingCurrentRouteMatch
           */
          protected $routeMatch;
          /**
           * Constructor.
           */
          public function __construct(CurrentRouteMatch $current_route_match) {
            $this->routeMatch = $current_route_match;
          }
          /**
           * {@inheritdoc}
           */
          static function getSubscribedEvents() {
            $events['kernel.response'] = ['handle'];
            return $events;
          }
          /**
           * This method is called whenever the kernel.response event is
           * dispatched.
           *
           * @param GetResponseEvent $event
           */
          public function handle(Event $event) {
            $route_name = $this->routeMatch->getRouteName();
            switch ($route_name) {
              case 'entity.node.canonical':
                $node = $this->routeMatch->getParameter('node');
                if ($this->redirectApplies($node)) {
                  $event->setResponse(new RedirectResponse($this->getRedirect($node)));
                }
            }
          }
          /**
           * Determines whether we should send a RedirectResponse for this node.
           */
           protected function redirectApplies(NodeInterface $node) {
            // One should have logic here returning TRUE or FALSE for whether we should redirect this response.
            $redirect_on = ['programas', 'servicios', 'aliados', 'testimonios', 'nosotros', 'nuestro_equipo', 'datos_de_contacto', 'banner', 'seccion'];
            return (in_array($node->getType(), $redirect_on));
        
          }
          protected function getRedirect(NodeInterface $node) {
            // We can cache this response when this is fixed: https://www.drupal.org/node/2573807
            // $response = CacheableRedirectResponse::create($url);
            // $response->addCacheableDependency($node);
            // return $response;
        
            switch ($node->getType()) {
              case 'nuestro_equipo':
                $url = "/profesionales";
                break;
        
              case 'datos_de_contacto':
                $url = "/contacto";
                break;
        
              case 'nosotros':
                $url = "/nosotros";
                break; 
        
              case 'banner':
                $url = "/";
                break;  
        
              case 'testimonios':
                $url = "/testimonios";
                break;
        
              case 'aliados':
                $url = "/aliados";
                break;
        
              default:
                $search_chars = array('á','é','í','ó','ú','ñ','Á','É','Í','Ó','Ú','Ñ',' ');
                $replace_chars= array('a','e','i','o','u','n','a','e','i','o','u','n','-');
                $node_title = str_replace($search_chars, $replace_chars, strtolower( $node->getTitle() ));
                $url = "/".$node->getType()."/".$node_title;
                break;
            }
            return $url;
          }
        }
        

        share|improve this answer

        share|improve this answer

        share|improve this answer

        answered Nov 29 at 17:32

        Mauricio

        133

        133

            draft saved
            draft discarded

            Thanks for contributing an answer to Drupal Answers!

            • Please be sure to answer the question. Provide details and share your research!

            But avoid

            • Asking for help, clarification, or responding to other answers.
            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.

            Some of your past answers have not been well-received, and you’re in danger of being blocked from answering.

            Please pay close attention to the following guidance:

            • Please be sure to answer the question. Provide details and share your research!

            But avoid

            • Asking for help, clarification, or responding to other answers.
            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.

            draft saved

            draft discarded

            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin(‘.new-post-login’, ‘https%3a%2f%2fdrupal.stackexchange.com%2fquestions%2f273233%2fhow-to-do-a-redirect-in-node-html-twig%23new-answer’, ‘question_page’);
            }
            );

            Post as a guest

            Required, but never shown

            Required, but never shown

            Required, but never shown

            Required, but never shown

            Required, but never shown

            Required, but never shown

            Required, but never shown

            Required, but never shown

            Required, but never shown

            Related Post

            Leave a Reply

            Your email address will not be published. Required fields are marked *