简体   繁体   中英

How can I print php variable in twig?

I want to make a twig template for my custom module that outputs Next and Previous article links.

In my .module file I have

<?php
/**
 * @file
 * Code for the nextprev module.
 */
 function nextprev_theme($existing, $type, $theme, $path) {
   return [
      'nextprev_template' => [
        'variables'=> [
                'nextprev' => 'Some_value',
            ],
    ],
  ];
  }

In my controller file I use

  public function build() {
    /**
      * {@inheritdoc}
      */

      $node = \Drupal::request()->attributes->get('node');
      $created_time = $node->getCreatedTime();
      $nextprevlinks .= $this->generateNext($created_time);
      $nextprevlinks .= $this->generatePrevious($created_time);

      $renderable = [
        '#theme' => 'nextprev_template',
        '#nextprev' => 'nextprevlinks',
      ];
      $rendered = drupal_render($renderable);

    }

}

I want to print out my $nextprevlinks in twig as {{ nextprev }}

I've made twig template within my module folder and it works, however I can't print out my {{ nextprev }} variable, it returns Null when I use kint.

I also added nextprev.routing.yml with:

nextprev.block:
  path: /node
  defaults:
    _controller: Drupal\nextprev\Controller\NextPrevLinksBlock::build
  requirements:
    _permission: 'access content'

This must work:

$renderable = [
    '#theme' => 'nextprev_template',
    '#nextprev' => $nextprevlinks,
  ];

But I think, it coild be better, if you return renderable array from controller like this:

return [
  '#theme' => 'nextprev_template',
  '#nextprev' => $nextprevlinks,
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM