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 Feb 25, 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

// Usage #1
$render->render(['controller' => ['Foo', 'bar', ['name' => 'Drupal']],]);

// Usage #2
$render->render([
  'controller' => ['Foo', 'bar'],
  'arguments' => ['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

All callbacks have to render keyed-array.

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

2.2 Use getVariables() method of controller class

If we use controller to render content, and no 'variables' defined in $data array, we can define getVariables() method in our controller.

<?php
class My_Controller {
  public function render($variables) {
    return "Hello {$variables['name']}";
  }

  public function getVariables() {
    return array('name' => 'Drupal');
  }
}

// Output: Hello Drupal
echo $render->render(array('controller' => ['My_Controller', 'render']));

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