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

查看:31
本文介绍了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 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

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

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