I got hook in my *.modules file php_invoke_preprocess_node that should print data from JSON according to node type. I need to print it to node content everytime i run it but now it runs only once and print it at the top of the site and then it won't run until I clear cache.

function php_invoke_preprocess_node(&$variables) {
$node = $variables['elements']['#node'];
//check content type
switch($node->getType()) {
  case 'nodeType':
    $session = getSession('','');
    $data = ['additonal JSON headers'];
    echo (CallAPI($data, $session)); //return JSON array that i want to print to node but i dont know how
  • if it is a dynamic variable you have to use lazy builder service. Also, use $variables['data'] = ['#type' => 'inline_template', '#template' => '<pre>{{ code|raw }}</pre>', '#context' => ['code' => var_export($data, TRUE)]];
    – user21641
    Jul 3, 2017 at 11:05
  • Ok i will try to use it but I never worked with it so i need to learn a bit and i will tell if it helped.
    – karoluS
    Jul 4, 2017 at 9:13

1 Answer 1


That was a hell of a problem to solve. I had to rebuild my code. Instead of hooks I took a bit different approach and I tried a solution proposed by @IvanJaros but I wasn't able to get lazy builders to work. I found that in drupal 7 there was a hook_init that was called everytime but it got deprecated in 8.
The answers are EventSubscribers, using them you can assign any function you want to specific event i.e. loading a page.

Here's a great tutorial that intruduce you to that feature.

Here's my event code

    class MyEventSubscriber implements EventSubscriberInterface{

        public static function getSubscribedEvents(){
        // Its called when respond transfer ended
        $events[KernelEvents::TERMINATE][] = ['onRespond',28];
        return $events;

  public function onRespond(FilterResponseEvent $event){ 
    $node = \Drupal::routeMatch()->getParameter('node');
    $user = \Drupal::currentUser();
    $name = $user->getUsername();

    $data = [];
        $nodeType = $node->getType();
            case 'nodeType':
                $soap_response = new JSonGetter();
                $data = $soap_response -> getUserData($name);
                echo('<script>var JSONarray = ' . print_r($faktury,1) . ';</script>');


  • Hi karoluS, as links can go down over time, could you include the essential part of the answer here and provide the link for reference (more information)? Jul 10, 2017 at 8:28
  • I don't see how this helps the initial question where you're trying to create a new template variable to output on a page.
    – Kevin
    Jul 10, 2017 at 10:34

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.