2

In drupal 7 we were able to resort to simple php functions in tpl.php files to load anything we wanted. Entities, blocks, view etc. This was really powerful for making really customisable blocks. In D7 we can use this php:

$block = block_load('views', 'block_name');      
$output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block   )))); 

When it comes to D8 I have read things about the getParameter but i'm coming up short on how to do it in a twig tpl.

For example, in a custom field in D8 I can get the node by using:

$node = \Drupal::routeMatch()->getParameter('node');

But how do I do this for a view on a page? And how would I do this in a twig.tpl in which you cannot write php?

I'm interested to see how people are tackling this in D8 or if I have the complete wrong method here.

1
  • You can print data parts of entities in a Twig template using the Twig syntax. Think of that as what you might of done with something like field_get_items or entity metadata wrapper in D7. You'll want to use devel Kint for that and enable Twig debugging. You can also create a variable with a preprocess function just as always in your theme's .theme file and then leverage that with Twig syntax in the template file. Mar 9 '16 at 3:00
0

better practice is to do that in preprocess functions !

so, fe. in preprocess page, you can access the node (if existing) via the $variables array and so on ..., then you add your own variables for the twig template, like:

$variables['my_fancy_block'] = \Drupal::service('renderer')->renderRoot($whatever);

and access this like:

{{ my_fancy_block }}
3
  • 1
    It's actually one step less: $variables['my_fancy_block'] = $whatever; is fine as render arrays are handled automatically in the template
    – Clive
    Mar 9 '16 at 10:51
  • Thanks Remy, that makes sense. It opens up another question to me, like is it a good idea to put all the preprocess function in .theme of make a a module for them, I might post another question for this. Mar 12 '16 at 11:57
  • this really depends on what you theme; usually you theme content from the site or other modules, so then you'll put it in your theme. if it comes form your module, and you want to style the output, then do it there - but this wont be theme specific styling, more UX stuff
    – rémy
    Mar 12 '16 at 20:18
0

To render a block in Twig template, you can use Twig tweak module for that, then you can use the following syntax:

  <dd>{{ drupal_block('myblock') }}</dd>

Related: How do I programmatically place a block?

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.