Twig中的{{exception.message}}无法呈现HTML [英] {{ exception.message }} in Twig doesn't render HTML

查看:46
本文介绍了Twig中的{{exception.message}}无法呈现HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在特定条件下引发 \ 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 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 ....
     }

}

并在 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}} ,并且还按照

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

在Twig中显示<​​code> \ Exception 消息时,如何使HTML正常工作?

How can I do to make HTML works when displaying the \Exception message in 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

这篇关于Twig中的{{exception.message}}无法呈现HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆