drls2738 2015-10-27 09:43
浏览 84

symfony2 utf8问题与控制器中的翻译有关

In my symfony 2 application, I am translating a string in a controller, from a yaml file, and sending it via ajax.

Then in my ajax function, I am parsing the response with JSON

The issue I have is the string that is being output by the translator is not in UTF8. Why? It is in the right format when I call the filter | trans in my templates.

Also, accentuated letters written in my controller are correctly sent in UTF8, it really seems to come from the translating component.

The workaround I found is to encode in UTF8 after it is translated in my controller, send it via ajax, then decode UTF8 in javascript. But it's not super clean plus I can get "this is not a URI" errors.

How can I have the translator output a UTF8 string in my controller ?

My yaml:

rights:
    is_boss: Tout éditer, voir, supprimer

My controller:

    $message= strtolower($translator->trans('rights.is_boss', array(), 'backend_pages'));

    $response = array(
        'message' => utf8_encode($message)
    );

    return new JsonResponse($this->get('serializer')->serialize($response, 'json'));

My view:

        $.ajax({
            type        : 'POST',
            url         : '{{ path('manage_rights', {'associate' : associate.id }) }}',
            data: {right: right, parameter: parameter, value: value},
            dataType: 'json'
        }).done(function(response){
            response = JSON.parse(response);
            var message = decodeURIComponent(escape(response.message));
            //do stuff
        })

The error I get if I don't encode in UTF 8 is the following:

Your data could not be encoded because it contains invalid UTF8 characters. 500 Internal Server Error - RuntimeException in vendor\jms\serializer\src\JMS\Serializer\JsonSerializationVisitor.php at line 36 -

Precision:

//This does not output a proper UTF8 string. I get an error if I try to serialize it in JSON
$message= strtolower($translator->trans('rights.is_boss', array(), 'backend_pages'));

//In my twig, this does output a correct string with accentuated chars without weird symbols
<label>{{ ('rights.is_boss') | trans }}</label>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 mmocr的训练错误,结果全为0
    • ¥15 python的qt5界面
    • ¥15 无线电能传输系统MATLAB仿真问题
    • ¥50 如何用脚本实现输入法的热键设置
    • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
    • ¥30 深度学习,前后端连接
    • ¥15 孟德尔随机化结果不一致
    • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
    • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
    • ¥15 谁有desed数据集呀