W3cubDocs

/Drupal 8

public function TwigExtension::renderVar

public TwigExtension::renderVar($arg)

Wrapper around render() for twig printed output.

If an object is passed which does not implement __toString(), RenderableInterface or toString() then 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.

Throws

\Exception When $arg is passed as an object which does not implement __toString(), RenderableInterface or toString().

See also

render

TwigNodeVisitor

File

core/lib/Drupal/Core/Template/TwigExtension.php, line 527

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)) {
    $this->bubbleArgMetadata($arg);
    if ($arg instanceof RenderableInterface) {
      $arg = $arg->toRenderable();
    }
    elseif (method_exists($arg, '__toString')) {
      return (string) $arg;
    }
    // You can't throw exceptions in the magic PHP __toString() methods, see
    // http://php.net/manual/language.oop5.magic.php#object.tostring so
    // we also support a toString method.
    elseif (method_exists($arg, 'toString')) {
      return $arg->toString();
    }
    else {
      throw new \Exception('Object of type ' . get_class($arg) . ' cannot be printed.');
    }
  }

  // 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);
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Template!TwigExtension.php/function/TwigExtension::renderVar/8.1.x