{{ exception.message }} in Twig doesn't render HTML

…衆ロ難τιáo~ 提交于 2020-01-13 16:27:00

问题


I have this controller where \Exception is raised (I haven't figured out which SF2 Exception to use yet) upon certain condition. Here is it:

<?php

namespace My\AppBundle\Controller;

use ....

class MyController extends Controller
{
     const EXCEPTION_MESSAGE = <<<EOF
My <b>HTML</b>
<br/>
<small>Small phrase</small>
EOF;

     public function indexAction()
     {
         // my logic

         if(in_array($data, $array))
             throw new \Exception(self::EXCEPTION_MESSAGE);

         // the rest of my logic

         return ....
     }

}

And in app/Resources/TwigBundle/views/Exception/error.html.twig

{% extends '::base.html.twig' %}

{% block body %}
    <h2>Error</h2>
    <p>{{ exception.message }}</p>
{% endblock %}

The problem is HTML is not rendered when seeing the error page in prod environement.

I tried {{ exception.message|raw }} and also setting autoescape to false as per this answer but it seems to have no effect.

How can I do to make HTML works when displaying the \Exception message in Twig?


回答1:


Where ever in the code you catch the exception is where it is needed to be added to the array you pass to twig. for example

$vars = [];
try {

    $a->indexAction();
    //fill $vars 


} catch (Exception $e) {
  $vars['exception'] = $e;
}

//pass $vars to twig


来源:https://stackoverflow.com/questions/29277456/exception-message-in-twig-doesnt-render-html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!