Gags Gags - 1 year ago 74
PHP Question

HTML is not rendered [Twig] / [Slim]

I am using twig as templating engine but my html is not rendering. All is displayed with the HTML tags itself.

Data from Database can be found by clicking here

I searched SO and got many posts that provides solution but none worked for me

below are the solutions:

  1. Use below code [not working]

    {{ detailArticle.artdesc|raw }}


    {% autoescape false %}
    {{ detailArticle.artdesc }}
    {% endautoescape %}

  2. Use filter and autoload like below [not working]

    $app->view = new \Slim\Views\Twig();
    $app->view->parserOptions = array(
    'debug' => 'true',
    'auto_reload' => true,
    'autoescape' => true
    $app->view->parserExtensions = array(new \Slim\Views\TwigExtension());

  3. Clear Twig cache [I do not have CLI on cPanel, so not sure how to do this]

    rm -rf app/cache/* OR rm -rf app/cache/prod/twig OR app/console cache:clear --env=prod

None of the solutions working for me. Please guide.

Data is displayed in same way you will see on the link mentioned above.

My composer.json is as below

"slim/slim": "~2.6",
"slim/views": "~0.1",
"twig/twig": "~1.16",
"panique/pdo-debug": "0.2",
"panique/php-sass": "~1.0",
"matthiasmullie/minify": "~1.3"
"Mini\\": "Mini"

Answer Source

I solved this same problem a few months ago. You need write this in your php:

$escaper = new Twig_Extension_Escaper(false);

My code

require_once 'path_to_Twig/Autoloader.php';

$loader = new Twig_Loader_Filesystem('path_to_views/');
$twig = new Twig_Environment($loader, array());

$escaper = new Twig_Extension_Escaper(false);

echo $twig->render($view_name, $data_to_view);

Steps with your code

  1. Download:
  2. Uncompress and place in you proyect.
  3. Write this in your file:
 require 'vendor/autoload.php'; 

 // Initialize Slim (the router/micro framework used) 
 $app = new \Slim\Slim(array( 
 'mode' => 'production' 

 require_once 'path_to_Twig/Autoloader.php'; //Substitute the Twig path, the path to the uncompress files in the project 

 $loader = new Twig_Loader_Filesystem('path_to_views/'); //Substitute with the path with the html files 
 $twig = new Twig_Environment($loader, array()); 

 $escaper = new Twig_Extension_Escaper(false); 

 echo $twig->render($view_name, $data_to_view); //First the name of the view html file, data that you want pass to the view in one array 

You need put all this whe you want render the view in the controller, that is to say, you substitute your code by this.