2

I'm on drupal 8, and I'm trying to figure out how to get the current node id in an override of views-view-unformatted.html.twig.

I have a view filled with titles with added links and I want to add a class to the one the corresponds to the current node id.

4 Answers 4

2

You will get the node id in an override of views-view-unformatted.html.twig. Find below code

{% for row in rows %}
  {% set nid  = row.content['#row']._entity.nid.value %}
{% endfor %}
1
  • It worked for me!
    – Talk2Nit
    Commented Mar 15, 2022 at 12:56
1

You'll find the node id from each row in _entity:

{{ row._entity.id }}
4
  • 2
    This doesn't seem to work.
    – John
    Commented Mar 14, 2018 at 18:41
  • 2
    Worked like a charm for me
    – pierostz
    Commented Dec 11, 2018 at 7:32
  • This does not work
    – sea26.2
    Commented Jun 10, 2020 at 21:26
  • @sea26.2 this answer is specific to the question (which template is used and how the View is configured). If you have a more complex use cases see for example drupal.stackexchange.com/questions/278890/…
    – 4uk4
    Commented Nov 7, 2021 at 10:26
1

I did this in preprocess
In your .theme file :

function YOURTHEME_preprocess_views_view_unformatted(&$variables) {
  foreach($variables['rows'] as $key => $row){
    if(is_object($row['content']['#node'])){
      $variables['rows'][$key]['nid'] = $row['content']['#node']->id();
    }  
  }
}

And then in your template file

{{ row.nid }}

Will output the NID.

1
0

Added class "active", if node_id same. enter image description here

In your .theme file :

function THEME_preprocess_views_view_unformatted__YOUR_NAME_VIEW__block_1(&$variables) {
  $node = \Drupal::request()->attributes->get('node');
  $node_id = $node->id();

  $view = $variables['view'];
  $rows = $variables['rows'];
  $id_view = $view->storage->id();

  if ($id_view == 'YOUR_NAME_VIEW' && $view->current_display == 'block_1') {
    $variables['#cache']['contexts'][] = 'url.path';

    foreach ($rows as $id => $row) {
      $view_node_id = $row['content']['#node']->id();

      if ($view_node_id == $node_id) {
        $variables['rows'][$id]['attributes']['class'][] = 'active';
      }

    }
  }

}

There is one condition!!! You need add any class in 'Row class' in your view.

FORMAT - Settings - Row class(The class to provide on each row.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.