You are here

public function TwigExtension::renderVar in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/lib/Drupal/Core/Template/TwigExtension.php \Drupal\Core\Template\TwigExtension::renderVar()

Wrapper around render() for twig printed output.

If an object is passed that has no __toString method an exception is thrown; other objects are casted to string. However in the case that the object is an instance of a Twig_Markup object it is returned directly to support auto escaping.

If an array is passed it is rendered via render() and scalar values are returned directly.

Parameters

mixed $arg: String, Object or Render Array.

Return value

mixed The rendered output or an Twig_Markup object.

See also

render

TwigNodeVisitor

File

core/lib/Drupal/Core/Template/TwigExtension.php, line 489
Contains \Drupal\Core\Template\TwigExtension.

Class

TwigExtension
A class providing Drupal Twig extensions.

Namespace

Drupal\Core\Template

Code

public function renderVar($arg) {

  // Check for a numeric zero int or float.
  if ($arg === 0 || $arg === 0.0) {
    return 0;
  }

  // Return early for NULL and empty arrays.
  if ($arg == NULL) {
    return NULL;
  }

  // Optimize for scalars as it is likely they come from the escape filter.
  if (is_scalar($arg)) {
    return $arg;
  }
  if (is_object($arg)) {
    if ($arg instanceof RenderableInterface) {
      $arg = $arg
        ->toRenderable();
    }
    elseif (method_exists($arg, '__toString')) {
      return (string) $arg;
    }
    elseif (method_exists($arg, 'toString')) {
      return $arg
        ->toString();
    }
    else {
      throw new \Exception(t('Object of type "@class" cannot be printed.', array(
        '@class' => get_class($arg),
      )));
    }
  }

  // This is a render array, with special simple cases already handled.
  // Early return if this element was pre-rendered (no need to re-render).
  if (isset($arg['#printed']) && $arg['#printed'] == TRUE && isset($arg['#markup']) && strlen($arg['#markup']) > 0) {
    return $arg['#markup'];
  }
  $arg['#printed'] = FALSE;
  return $this->renderer
    ->render($arg);
}