public function TwigExtension::renderVar in Drupal 9
Same name and namespace in other branches
- 8 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
File
- core/
lib/ Drupal/ Core/ Template/ TwigExtension.php, line 522
Class
- TwigExtension
- A class providing Drupal Twig extensions.
Namespace
Drupal\Core\TemplateCode
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;
}
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);
}