在自定义细枝过滤器中将字符串替换为锚点(渲染问题)


Replace String with Anchor in Custom Twig Filter (Rendering issue)

我正在为我的网站编写一个自定义的小树枝过滤器,除其他外,它会解析一些文本中的URL,如果找到它们,它应该用指向自己的锚标记来替换令牌。

代码:

foreach ($tokens as $key=>$value)
{
  if (filter_var($value, FILTER_VALIDATE_URL))
  {
    // Replace $token with a version anchored to itself
    $tokens[$key] = "<a href='$value' target='_blank'>".$value."</a>";
  }
}
// Replace the spaces back in the string and return it
return implode(" ", $tokens);

解析和替换似乎很好,但在渲染时,Twig并没有将替换后的令牌渲染为锚点,而是将其渲染为字符串(这意味着我在页面上看到html渲染为文本)。

有什么解决方案吗?

您可以使用trick的原始过滤器来避免逃离函数的输出:

{{ my_function(myVar)|raw }}

请参阅文档:http://twig.sensiolabs.org/doc/filters/raw.html