allejo
allejo

Reputation: 2203

Returning raw HTML from a function without a Twig filter

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?

Upvotes: 15

Views: 9267

Answers (3)

SilvioQ
SilvioQ

Reputation: 2072

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

Upvotes: 29

Armando Juarez
Armando Juarez

Reputation: 323

I'm writing this in support of SilvioQ's answer, which worked perfectly for me.

In my case I'm creating a filter to add a Stylesheet tag in a header block without having to worry about either hard-coding the base-url or having to pass it as a parameter to the view when it's not needed. SilvioQ's code works just fine and helps keep my view a little less cluttered.

Here's how I'm using it in my code:

class AppExtension extends AbstractExtension
{

    public function getFilters() {
        return array(
            new TwigFilter('css', array($this, 'cssLinkFilter')),
        );
    }

    public function cssLinkFilter($cssName){
        $link = sprintf('', getBaseURL(true), $cssName);
        return new \Twig_Markup($link, 'UTF-8');
    }
}

I'm still working on this, I also need another one for Javascript. If I change my code or figure it doesn't work I'll update my answer.

Upvotes: 0

Francesco Abeni
Francesco Abeni

Reputation: 4265

Shortly, no, there is not.

Twig is the rendering engine so whatever you return from any of your method will be parsed by Twig and escaped unless you use the raw filter or you turn off the autoescape in Twig (see this answer).

Upvotes: -1

Related Questions