Answers:
到您访问该参数时,该参数将从nid向上映射到完整节点对象,因此:
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
// You can get nid and anything else you need from the node object.
$nid = $node->id();
}
有关更多信息,请参见更改记录。
/taxonomy/term/{tid}
?
menu_get_object
吗?
{}
在路由中编写的任何内容。对于分类术语,称为路径参数taxonomy_term
,即路径定义/taxonomy/term/{taxonomy_term}
。在这里,您可以像这样获得它\Drupal::routeMatch()->getParameter('taxonomy_term')
。
如果您正在使用或创建自定义块,则必须遵循以下代码来获取当前的URL节点ID。
// add libraries
use Drupal\Core\Cache\Cache;
// code to get nid
$node = \Drupal::routeMatch()->getParameter('node');
$node->id() // get current node id (current url node id)
// for cache
public function getCacheTags() {
//With this when your node change your block will rebuild
if ($node = \Drupal::routeMatch()->getParameter('node')) {
//if there is node add its cachetag
return Cache::mergeTags(parent::getCacheTags(), array('node:' . $node->id()));
} else {
//Return default tags instead.
return parent::getCacheTags();
}
}
public function getCacheContexts() {
//if you depends on \Drupal::routeMatch()
//you must set context of this block with 'route' context tag.
//Every new route this block will rebuild
return Cache::mergeContexts(parent::getCacheContexts(), array('route'));
}
请注意,在节点预览页面上,以下操作无效:
$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->id();
对于节点预览页面,必须以这种方式加载节点:
$node = \Drupal::routeMatch()->getParameter('node_preview');
$nid = $node->id();