从没有 Twig 过滤器的函数中返回原始 HTML [英] Returning raw HTML from a function without a Twig filter
问题描述
我有一个具有返回 HTML 的函数的类.
I have a class that has a function that returns HTML.
class MyParser {
public function getHTML() {
return '<a href="#">Hello World</a>';
}
}
然后在我的 Twig 模板中,我使用 raw
过滤器来输出文字 HTML,而不是让 Twig 为我转义它:
And then in my Twig template, I use the raw
filter to output the literal HTML instead of having Twig escape it for me:
{{ myParserInstance.HTML | raw }}
有没有函数的方法(这不是 Twig 过滤器或函数) 返回原始 HTML 并按原样呈现?或者我将如何创建一个 Twig 过滤器或函数来为我无缝地执行此操作?
Is there a way for a function (that's not a Twig Filter or Function) to return raw HTML and render it as such? Or how would I go about creating a Twig Filter or Function that does this seamlessly for me?
例如,我不会想要这样的东西:
For example, I wouldn't want something like:
{{ render(myParserInstance) }}
相反,我只想能够使用 HTML
函数调用.这是可能的,还是我坚持使用 Twig 函数或使用 |原始
?
Instead, I would like to just be able to use the HTML
function call. Is this at all possible or am I stuck with a Twig function or using | raw
?
推荐答案
您可以安全地返回和 Twig_Markup 对象对象...
You can return and Twig_Markup object object in safe way ...
class MyParser {
public function getHTML() {
$rawString = '<a href="#">Hello World</a>'
return new \Twig_Markup( $rawString, 'UTF-8' );
}
}
或
class MyParser {
public function getHTML() {
$rawString = '<a href="#">Hello World</a>'
return new \Twig\Markup( $rawString, 'UTF-8' );
}
}
这篇关于从没有 Twig 过滤器的函数中返回原始 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!