When on a node, the following annotation will obtain the node from the context:
/**
* @Condition(
* id = "node_type",
* label = @Translation("Node Bundle"),
* context = {
* "node" = @ContextDefinition("entity:node", label = @Translation("Node"))
* }
* )
*/
As shown here: https://www.drupal.org/docs/8/api/plugin-api/plugin-contexts
Is there an equivalent way to do this with taxonomy terms when on /taxonomy/term/%?
The code below certainly works but I'm wondering if there is a cleaner method like for nodes. Note that I'm also aware of the Term::load($tid)
method but that still requires parsing the URL to obtain the tid and isn't portable (the code can be used only when run on a page).
/**
* Return current term.
*/
public function getCurrentTerm() {
$term = null;
// Below we are using the general method to obtain the objects.
// \Drupal\taxonomy\Entity\Term::load($tid) is the other
// Get the unaliased path in the form /taxonomy/term/tid.
$current_path = \Drupal::service('path.current')->getPath();
preg_match('/\/taxonomy\/term\/\d+/', $current_path, $matches);
// Return null if not in proper form.
if (count($matches)) {
// Find the parameters for this route.
$params = \Drupal\Core\Url::fromUri("internal:" . $current_path)
->getRouteParameters();
// Fetch the taxonomy object.
$entity_type = key($params);
$term = \Drupal::entityTypeManager()
->getStorage($entity_type)
->load($params[$entity_type]);
}
return $term;
}
}
$term = \Drupal::routeMatch()->getParameter('taxonomy_term')