function TwigExtension::renderVar

Same name in other branches
  1. 9 core/lib/Drupal/Core/Template/TwigExtension.php \Drupal\Core\Template\TwigExtension::renderVar()
  2. 8.9.x core/lib/Drupal/Core/Template/TwigExtension.php \Drupal\Core\Template\TwigExtension::renderVar()
  3. 10 core/lib/Drupal/Core/Template/TwigExtension.php \Drupal\Core\Template\TwigExtension::renderVar()

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 a \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 535

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, empty arrays, empty strings and FALSE booleans.
    // @todo https://www.drupal.org/project/drupal/issues/3240093 Determine if
    //   this behavior is correct or should be deprecated.
    if ($arg == NULL) {
        return '';
    }
    // 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;
        }
        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);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.