Twig 中的 {{ exception.message }} 不呈现 HTML

2022-01-22 00:00:00 php symfony html twig

我有这个控制器,其中 Exception 在特定条件下引发(我还没有弄清楚要使用哪个 SF2 Exception).就是这样:

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 MyAppBundleController;

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

}

并且在 app/Resources/TwigBundle/views/Exception/error.html.twig

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

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

问题是在 prod 环境中看到错误页面时没有呈现 HTML.

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

我尝试了 {{ exception.message|raw }} 并将 autoescape 设置为 false 根据 this answer但似乎没有效果.

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

在 Twig 中显示 Exception 消息时如何使 HTML 正常工作?

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

推荐答案

在代码中捕获异常的地方就是需要将其添加到传递给 twig 的数组中的地方.例如

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

相关文章