• 7
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

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?

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' );
    }
}
  • 17
Reply Report

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.

  • 0
Reply Report

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

  • -1
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions