Skip to content
This repository was archived by the owner on Feb 17, 2022. It is now read-only.

7.x 2.x helper content render

Andy Truong edited this page Jan 17, 2014 · 17 revisions

1. Basic rendering

Note that, $render used below is object from at_container('helper.content_render').

1.1. Render a string

<?php
$render->render('Hello Drupal!');

1.2. Render content with function callback

<?php
$render->render(array(
  'function' => 't', 
  'arguments' => array('Hello Drupal!')
));

1.3. Render content with a Twig template

<?php
$render->render(array(
  'template' => '@my_module/templates/hello.html.twig', 
  'variables' => array('name' => 'Drupal')
));

1.4. Render content with class

<?php
$render->render(array(
  'controller' => ['Foo', 'bar'],
  'arguments' => array('name' => 'Drupal')
));

1.5. Render content with Twig string template

<?php
$render->render(array(
  'template_string' => 'Hello {{ name|t }}', 
  'variables' => array('name' => 'Drupal')
));

2. Dynamic variables

To avoid complex logic in our templates/controller, we can pre-process the variables.

2.1. Use callback for variables

Use callback to render keyed-array.

Use service:method

<?php
$render->render(array(
  'template' => '@my_module/templates/hello.html.twig', 
  'variables' => 'service_name:service_method'
));

Use function

<?php
$render->render(array(
  'template' => '@my_module/templates/hello.html.twig', 
  'variables' => 'my_callback'
));

Use object/method

<?php
$render->render(array(
  'template' => '@my_module/templates/hello.html.twig', 
  'variables' => [$obj, 'method']
));

Use class/method

<?php
$render->render(array(
  'template' => '@my_module/templates/hello.html.twig', 
  'variables' => ['Class_Name', 'method']
));

3. Cache rendered-output

If the output is expensive, we can cache it:

<?php
$output = $render->render(array(
  'template_string' => '{{ view_name|drupalView }}',
  'variables' => array('view_name' => 'latest_products'),
  'cache' => array(
    'id' => 'products:latest:front',
    'ttl' => '+ 30 minutes',
    'tags' => ['node', 'products', 'home']
  )
));

Clone this wiki locally