How to do a redirect in node.html.twig?
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
add a comment |
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
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 '18 at 15:08
Did you try just having a Views path set tonode/%nidto overtake content?
– Kevin
Nov 29 '18 at 15:11
add a comment |
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
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
8 redirect
edited Nov 29 '18 at 18:48
Pierre.Vriens
35.3k1336155
35.3k1336155
asked Nov 29 '18 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 '18 at 15:08
Did you try just having a Views path set tonode/%nidto overtake content?
– Kevin
Nov 29 '18 at 15:11
add a comment |
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 '18 at 15:08
Did you try just having a Views path set tonode/%nidto overtake content?
– Kevin
Nov 29 '18 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 '18 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 '18 at 15:08
Did you try just having a Views path set to
node/%nid to overtake content?– Kevin
Nov 29 '18 at 15:11
Did you try just having a Views path set to
node/%nid to overtake content?– Kevin
Nov 29 '18 at 15:11
add a comment |
3 Answers
3
active
oldest
votes
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.
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 '18 at 16:53
This method works perfectly, i used and modified a few this code and works finally @kevin
– Mauricio
Nov 29 '18 at 17:22
add a comment |
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
It looks like its a function in CraftCMS but not in Twig itself. docs.craftcms.com/v2/templating/redirect.html
– Kevin
Nov 29 '18 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 '18 at 15:27
add a comment |
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;
}
}
add a comment |
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',
autoActivateHeartbeat: false,
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
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 '18 at 16:53
This method works perfectly, i used and modified a few this code and works finally @kevin
– Mauricio
Nov 29 '18 at 17:22
add a comment |
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.
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 '18 at 16:53
This method works perfectly, i used and modified a few this code and works finally @kevin
– Mauricio
Nov 29 '18 at 17:22
add a comment |
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.
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.
edited Nov 29 '18 at 15:52
answered Nov 29 '18 at 15:08
Kevin
17.4k848108
17.4k848108
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 '18 at 16:53
This method works perfectly, i used and modified a few this code and works finally @kevin
– Mauricio
Nov 29 '18 at 17:22
add a comment |
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 '18 at 16:53
This method works perfectly, i used and modified a few this code and works finally @kevin
– Mauricio
Nov 29 '18 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 '18 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 '18 at 16:53
This method works perfectly, i used and modified a few this code and works finally @kevin
– Mauricio
Nov 29 '18 at 17:22
This method works perfectly, i used and modified a few this code and works finally @kevin
– Mauricio
Nov 29 '18 at 17:22
add a comment |
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
It looks like its a function in CraftCMS but not in Twig itself. docs.craftcms.com/v2/templating/redirect.html
– Kevin
Nov 29 '18 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 '18 at 15:27
add a comment |
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
It looks like its a function in CraftCMS but not in Twig itself. docs.craftcms.com/v2/templating/redirect.html
– Kevin
Nov 29 '18 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 '18 at 15:27
add a comment |
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
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
answered Nov 29 '18 at 15:08
Leigh Mason
1,426146
1,426146
It looks like its a function in CraftCMS but not in Twig itself. docs.craftcms.com/v2/templating/redirect.html
– Kevin
Nov 29 '18 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 '18 at 15:27
add a comment |
It looks like its a function in CraftCMS but not in Twig itself. docs.craftcms.com/v2/templating/redirect.html
– Kevin
Nov 29 '18 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 '18 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 '18 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 '18 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 '18 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 '18 at 15:27
add a comment |
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;
}
}
add a comment |
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;
}
}
add a comment |
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;
}
}
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;
}
}
answered Nov 29 '18 at 17:32
Mauricio
133
133
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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 '18 at 15:08
Did you try just having a Views path set to
node/%nidto overtake content?– Kevin
Nov 29 '18 at 15:11