如何 HTML 编码/转义字符串?有内置的吗?

问题描述:

我有一个不受信任的字符串,我想在 HTML 页面中显示为文本.我需要将字符 '<' 和 '&' 转义为 HTML 实体.越少越好.

I have an untrusted string that I want to show as text in an HTML page. I need to escape the chars '<' and '&' as HTML entities. The less fuss the better.

我使用的是 UTF8,不需要其他实体来表示重音字母.

I'm using UTF8 and don't need other entities for accented letters.

Ruby 或 Rails 中是否有内置函数,还是应该自己编写?

Is there a built-in function in Ruby or Rails, or should I roll my own?

h 辅助方法:

<%=h "<p> will be preserved" %>