0

I want to pass variable to js for my custom page. Tried below code which is working fine with static value. But I m not able do same thing with existing variable of custom template.

 function test_theme($existing, $type, $theme, $path) { return [ 'test_template' => [ 'variables' => [ 'nDetails' => null ], ], ]; } function test_preprocess_page(&$variables) { print_r($variables['nDetails']); // its showing empty??? $routeName = \Drupal::routeMatch()->getRouteName(); if ($routeName == 'test.content') { $variables['#attached']['drupalSettings']['test']['data'] = $variables['nDetails']; $variables['#attached']['drupalSettings']['test']['dataa'] = "work fine"; } } class TestController extends ControllerBase { public function content() { return [ '#theme' => 'test_template', '#nDetails' => "test1" ]; } 

Is something wrong with above code? Or there is another way to pass variable to drupal setting from controller itself?

1 Answer 1

0

You only see the variable in the preprocess hook of the custom template hook_preprocess_test_template(). But you don't need a preprocess hook at all, because you can attach the drupal settings in the controller directly:

return [ '#theme' => 'test_template', '#attached' => [ 'drupalSettings' => [ 'test' => [ 'data' => 'test1', ], ], ], ]; 
1
  • This is exactly what I needed. Thanks its work perfectly. Commented May 16, 2018 at 8:45

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.