InlineTemplate.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace Drupal\Core\Render\Element;
  3. /**
  4. * Provides a render element where the user supplies an in-line Twig template.
  5. *
  6. * Properties:
  7. * - #template: The inline Twig template used to render the element.
  8. * - #context: (array) The variables to substitute into the Twig template.
  9. * Each variable may be a string or a render array.
  10. *
  11. * Usage example:
  12. * @code
  13. * $build['hello'] = [
  14. * '#type' => 'inline_template',
  15. * '#template' => "{% trans %} Hello {% endtrans %} <strong>{{name}}</strong>",
  16. * '#context' => [
  17. * 'name' => $name,
  18. * ]
  19. * ];
  20. * @endcode
  21. *
  22. * @RenderElement("inline_template")
  23. */
  24. class InlineTemplate extends RenderElement {
  25. /**
  26. * {@inheritdoc}
  27. */
  28. public function getInfo() {
  29. $class = get_class($this);
  30. return [
  31. '#pre_render' => [
  32. [$class, 'preRenderInlineTemplate'],
  33. ],
  34. '#template' => '',
  35. '#context' => [],
  36. ];
  37. }
  38. /**
  39. * Renders a twig string directly.
  40. *
  41. * @param array $element
  42. *
  43. * @return array
  44. */
  45. public static function preRenderInlineTemplate($element) {
  46. /** @var \Drupal\Core\Template\TwigEnvironment $environment */
  47. $environment = \Drupal::service('twig');
  48. $markup = $environment->renderInline($element['#template'], $element['#context']);
  49. $element['#markup'] = $markup;
  50. return $element;
  51. }
  52. }