0

On Drupal 8, I want pass a variable to a overrides template from my controller OR from the hook theme. I do several tries :

from my .module file :

function ms_story_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['page__ms_story__global'] = array(
    'variables' => [
      'toto' => "toto", //try one
    ],
    'base hook' => 'page',
    'render element' => 'elements',
    '#tata' => 'tata', //try two
  );
  return $theme;
}

from my .php controller file :

class customController extends ControllerBase {
  public function map_global($name) {
    return [
      '#type' => 'markup',
      '#theme' => 'page__ms_story__global',
      '#markup' => $this->t("Implement method: hello with parameter(s): $name"),
      '#tutu' => "tutu", //try three
      'variables' => [
        "tyty" => "tyty", //try four
      ],
    ];
  }
}

But when I want display all available variable from my overrided template file (via {{ kint() }} ), I don't see anywhere variables I want add. Variables 'toto' 'tata' tutu' and 'tyty' aren't present in the array structure displayed via kint (I cleared all cache of course)

Where is my mystake ?

Bonus question : how can I add a variable who use not any cache ? (the variable is calculated again every time the user load page ?

1

You cannot use #markup and #theme in the same element. #markup will always take precedence, and #theme is ignored. If you want to output some markup, you need to include that as part of your theme. If the markup is dynamic, then include it as a variable to be passed to your theme (though you need to name the variable as something other than markup).

You've also defined the variable as toto in your hook_theme() implementation, then passed the value in #tutu in your render array. You need to use '#toto' => 'some value'.

  • Thanks for your help =) I tried with the '#markup' commented , I tried also with the line '#type' commented but the custom variable doesn't appears in the {{ kint() }} array :/ – user2137454 Apr 30 '17 at 8:14
  • Because in your hook_theme, you defined the variable as toto, and in your theme implementation you've defined it as #tutu. These need to match. You need to use #toto => 'some value'. – Jaypan Apr 30 '17 at 9:17
  • @Jaypan The last comment you wrote should be included in the answer. – kiamlaluno Apr 30 '17 at 12:42

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.