0

I'm attempting to pass some data from a block module into a template. I've found that I can make up a render array property and then access it in the template. Here is an example of my code:

class MyBlock extends BlockBase {            
      return [        
        '#firstname' => 'John',
        '#lastname' => 'Doe',
      ];        
    }

I can access this data in the twig templeate by using:

{{ elements.myblock.content['#firstname'] }}
{{ elements.myblock.content['#lastname'] }}

Is this an acceptable means for passing data into a template? All the other examples I've found have the render arrays being picked up by a hook_theme function and then getting passed to the template. The method I show above seems simpler and I'm wondering if there is something problematic with doing it this way.

Thanks!

1
  • I think your approach is fine, except best practice would be that your twig template would exist in the same module as where you are creating the block.
    – 100pic
    Commented Mar 27, 2019 at 6:07

1 Answer 1

0

If you pass the variables like the following:

class MyBlock extends BlockBase {
  public function build() {
    return [
      '#firstname' => 'John',
      '#lastname' => 'Doe',
    ];
  }
}

You can access to your variables #firstname and #lastname like:

{{ content['#firstname'] }}
{{ content['#lastname'] }}
1
  • Thank you, this is helpful. Commented Mar 29, 2019 at 0:12

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.