How to use utf-8 encoded data in erb template

2019-02-25 12:33发布

I have an data-file stored with utf-8 encode, and I want to embed the data to an erb template. The data-file is explicitly encoded with utf-8 at the top. But while running the erb engine but I encounter Encoding::CompatibilityError Error.

I thought as the default encoding in Ruby is ASCII, the erb template must also encoded under ascii. I have explicitly changed it to utf-8 but there is no good.

Here is the data-file:

# coding: utf-8

samples: [
    { name: '北京', city: '北京' }
]

Here is the Erb template:

<% # -*- coding: UTF-8 -*- %>
#...
<p><%= samples[:name] %></p>

4条回答
我只想做你的唯一
2楼-- · 2019-02-25 13:01

If you're using Rails, have you configured default encoding, in application.rb? like:

config.encoding = "utf-8"

My Rails (3.2.1) project does not contain any configuration other than that.

Other thing you want to check is, whether your datafile really in UTF-8 or not. If you're using Unix-like system, you can use 'nkf' command to check the code, by:

nkf --guess FILE_NAME
查看更多
手持菜刀,她持情操
3楼-- · 2019-02-25 13:12

In the scenario where you have an ERB template rendering strings from another file that is in UTF-8, adding the following to the top of the ERB template solved it for me:

<%# coding: UTF-8 %>

(instead of <% # -*- coding: UTF-8 -*- %>)

查看更多
劫难
4楼-- · 2019-02-25 13:22

Specify <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> in the header of the template

查看更多
爷、活的狠高调
5楼-- · 2019-02-25 13:26

(I decided to write different answer)

Two issues, I think.

  • datafile encoding on input
  • how you output

The erb library knows about the encoding specification in magic comments, but the data file part, you need to take care by yourself. So, when you read the file, you have to specify encoding, or specify default encoding beforehand.

On output, you need to specify the encoding for output. You can specify per I/O channel basis.

To specify default encoding (easiest), you can:

Encoding.default_external = "UTF-8"

to use UTF-8 for all I/O.

查看更多
登录 后发表回答