Gags Gags - 7 months ago 21
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 }}

    or

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

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

    $app->view = new \Slim\Views\Twig();
    $app->view->setTemplatesDirectory("application/view");
    $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

{
"name":"panique/mini2",
"homepage":"https://github.com/panique/mini2",
"license":"MIT",
"require":{
"php":">=5.3.0",
"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"
},
"autoload":{
"psr-4":{
"Mini\\": "Mini"
}
}
}

Answer

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

$escaper = new Twig_Extension_Escaper(false);
$app->view->addExtension($escaper);

My code

require_once 'path_to_Twig/Autoloader.php';
Twig_Autoloader::register();

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

$escaper = new Twig_Extension_Escaper(false);
$twig->addExtension($escaper);

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

Steps with your code

  1. Download: http://pear.twig-project.org/get/Twig-1.24.0.tgz
  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 
 Twig_Autoloader::register(); 

 $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); 
 $twig->addExtension($escaper); 

 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.