1

I'm currently using the starter module which adds the Twig function place_view(). This works well in most cases, however I'd like to be able to pass another parameter to populate the fixed value given in a contextual filter.

This would be my contextual filter settings: Contextual filter settings

Here's the place_view() Twig function:

public function place_view($name, $display_id = 'default') {
  $drupal = \Drupal::service('renderer');
  $view = views_embed_view($name, $display_id);

  if(! is_null($view)) {
    return $drupal->render($view);
  }

  return null;
}

Preferably I'd like to be able to use place_view() with a parameter to adjust that fixed value. It'd be even better if I could somehow reference the contextual filter I wanted to adjust the fixed value of.

Hopefully that all made sense, thanks in advance.

1 Answer 1

3

Use views_embed_view:

function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  // Remove $name and $display_id from the arguments.
  unset($args[0], $args[1]);

  $view = Views::getView($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return [
    '#type' => 'view',
    '#name' => $name,
    '#display_id' => $display_id,
    '#arguments' => $args,
  ];
}

Btw. Twig Tweak maps this function one to one:

  {# This accepts views arguments as well. #}
  <dt>View:</dt>
  <dd>{{ drupal_view('view_name', 'page_1') }}</dd>

Example

So if you want to filter the node 123 in the contextual filter you've shown in the question, you use this as third argument:

PHP

views_embed_view('view_name', 'block_1', '123');

TWIG (using the module Twig Tweak)

{{ drupal_view('view_name', 'block_1', '123') }}
4
  • Thanks, this is useful. I'm still having trouble actually accessing these extra arguments inside the view though. As shown in my screenshot, I'd like to alter the 'Default Value' contextual filter, or use a different filter that allows me to pass a value from my template. Apr 10, 2017 at 10:33
  • I've added an example.
    – 4uk4
    Apr 10, 2017 at 11:56
  • In my screenshot I have the default value set to 'Fixed'. Surely passing a random parameter of some numbers won't replace my given value in the view settings with the one provided in the drupal_view() function? Apr 10, 2017 at 14:35
  • Yes, it will replace the default value.
    – 4uk4
    Apr 10, 2017 at 15:22

Your Answer

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

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