1

Situation:

  • A view has a contextual filter on a field named type.

  • The view sorts by date and has the pager set to display 1 item (I want only the newest node).

  • I want to show type + the node title as the view title.

  • So, what I want to put in the Override title field is

    {{ arguments.field_type_value }} {{ title }}

But {{ title }} doesn't work. It outputs nothing. This isn't a surprise because (a) {{ title }} isn't in the Replacement Patterns list and (b) I assume the view expects to display multiple nodes, so there isn't just one {{ title }} to display.

Is there a straightforward way to do what I want to do using a view as I'm doing? There are reasons why I want to use a view.

UPDATE:

  • The view is set to Show: Content so I can use a Twig template I created. (I added this update after seeing No Sssweat's first two suggestions below that work perfectly for Show: Fields but don't work for Show: Content. Note that No Sssweat also gives a solution for the Show: Content situation.)
2

Simply add title as a field and checkmark hide from display, now {{ title }} should work despite not being listed as replacement pattern.

Also make sure your view's title is set to none

enter image description here


Alternatively, you could also solve it by not overriding it in the contextual filter settings and instead overwrite it directly in the view's title.

Add title and type as fields, hide them if you want/need to.

enter image description here


But, if you're using teaser

The above two solutions won't work, so you can solve it programmatically:

/**
 * Implements hook_views_post_render()
 */
function mymodule_views_post_render($view) {
  if ($view->id() == "view_name" && $view->current_display == 'page_1') {
    $node = $view->result[0]->_entity;
    $new_title = $node->type->entity->label() . ' ' . $node->getTitle();
    $view->setTitle($new_title);
  }
}
1
  • 1
    Thanks, @No Sssweat. I'm using Show: Content, so I updated my question to reflect that. Your coded solution worked perfectly for me. I also tested your first two solutions with Show: Fields and they work in that case as well. I've never used views_post_render before. And I had no idea Twig syntax can be used in a title field, so I learned something new there as well! Nov 10 '20 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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