Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning raw HTML from a function without a Twig filter

Tags:

php

twig

I have a class that has a function that returns HTML.

class MyParser {
    public function getHTML() {
        return '<a href="#">Hello World</a>';
    }
}

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 }}

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) }}

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?

like image 279
allejo Avatar asked Apr 08 '16 20:04

allejo


1 Answers

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' );
    }
}

or

class MyParser {
    public function getHTML() {
         $rawString = '<a href="#">Hello World</a>'
         return new \Twig\Markup( $rawString, 'UTF-8' );
    }
}
like image 167
SilvioQ Avatar answered Sep 24 '22 14:09

SilvioQ