Commit a53d5aaf authored by Alex Pott's avatar Alex Pott
Browse files

Issue #2540870 by joelpittet, lauriii: Improve the |safe_join Twig to be...

Issue #2540870 by joelpittet, lauriii: Improve the |safe_join Twig to be inline with twig_join_filter()
parent 5dc2bd06
Loading
Loading
Loading
Loading
+6 −2
Changes for core/lib/Drupal/Core/Template/TwigExtension.php: 6 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -534,7 +534,7 @@ public function renderVar($arg) {
   *
   * @param \Twig_Environment $env
   *   A Twig_Environment instance.
   * @param mixed[]|\Traversable $value
   * @param mixed[]|\Traversable|NULL $value
   *   The pieces to join.
   * @param string $glue
   *   The delimiter with which to join the string. Defaults to an empty string.
@@ -545,10 +545,14 @@ public function renderVar($arg) {
   *   The strings joined together.
   */
  public function safeJoin(\Twig_Environment $env, $value, $glue = '') {
    if ($value instanceof \Traversable) {
      $value = iterator_to_array($value, false);
    }

    return implode($glue, array_map(function($item) use ($env) {
      // If $item is not marked safe then it will be escaped.
      return $this->escapeFilter($env, $item, 'html', NULL, TRUE);
    }, $value));
    }, (array) $value));
  }

}
+14 −0
Changes for core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php: 14 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -200,6 +200,20 @@ public function testSafeJoin() {
    ];
    $result = $twig_extension->safeJoin($twig_environment, $items, '<br/>');
    $this->assertEquals('&lt;em&gt;will be escaped&lt;/em&gt;<br/><em>will be markup</em><br/><strong>will be rendered</strong>', $result);

    // Ensure safe_join Twig filter supports Traversable variables.
    $items = new \ArrayObject([
      '<em>will be escaped</em>',
      $markup,
      ['#markup' => '<strong>will be rendered</strong>'],
    ]);
    $result = $twig_extension->safeJoin($twig_environment, $items, ', ');
    $this->assertEquals('&lt;em&gt;will be escaped&lt;/em&gt;, <em>will be markup</em>, <strong>will be rendered</strong>', $result);

    // Ensure safe_join Twig filter supports empty variables.
    $items = NULL;
    $result = $twig_extension->safeJoin($twig_environment, $items, '<br>');
    $this->assertEmpty($result);
  }

  /**