ใน Drupal 7 ถ้าฉันต้องการรับ node id ของโหนดที่แสดงอยู่ในปัจจุบัน (เช่นnode/145) ฉันจะได้มันมาพร้อมกับarg()ฟังก์ชั่น ในกรณีนี้arg(1)จะกลับ 145
ฉันจะประสบความสำเร็จใน Drupal 8 ได้อย่างไร
ใน Drupal 7 ถ้าฉันต้องการรับ node id ของโหนดที่แสดงอยู่ในปัจจุบัน (เช่นnode/145) ฉันจะได้มันมาพร้อมกับarg()ฟังก์ชั่น ในกรณีนี้arg(1)จะกลับ 145
ฉันจะประสบความสำเร็จใน Drupal 8 ได้อย่างไร
คำตอบ:
พารามิเตอร์จะได้รับการถ่ายทอดจาก 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หรือไม่?
                    {}ในเส้นทางของคุณ สำหรับคำอนุกรมวิธาน paramater เส้นทางที่เรียกว่านิยามเส้นทางtaxonomy_term ที่นี่คุณจะได้รับมันเช่นนี้/taxonomy/term/{taxonomy_term} \Drupal::routeMatch()->getParameter('taxonomy_term')
                    \Drupal::routeMatch()->getParameter('node')มันเป็นความถูกต้องในการใช้ \Drupal::routeMatch()->getRawParameter('node')หากคุณเพียงแค่ต้องใช้รหัสโหนดคุณสามารถใช้
หากคุณกำลังใช้หรือสร้างบล็อกที่กำหนดเองคุณต้องทำตามรหัสนี้เพื่อรับรหัสโหนด url ปัจจุบัน
// 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();