Calling ERB without Rails: undefined method 'r

2019-06-20 05:07发布

I am using the ERB engine to generate an offline HTML version of a page of my Rails website. The page shows great when shown by Rails, but I have trouble generating with ERB by myself (despite using the same ERB template).

First I was getting the error undefined method 't' and I solved it by replacing all <%=t(...)%> calls with <%=I18n.translate(...)%>.

Now I get undefined method 'raw'. Should I replace all <%=raw(...)%> calls with something else? If yes, what?

2条回答
女痞
2楼-- · 2019-06-20 05:40

raw is defined as helper in actionpack/action_view library so that without rails you can't use it. But ERB templating shows its output without any escaping:

require 'erb'
@person_name = "<script>name</script>"
ERB.new("<%= @person_name %>").result # => "<script>name</script>" 

And because of this for purpose of escaping there is ERB::Util#html_escape method

include ERB::Util
ERB.new("<%= h @person_name %>").result # => "&lt;script&gt;name&lt;/script&gt;" 
查看更多
做个烂人
3楼-- · 2019-06-20 05:49

While @warhog 's answer will work, the include isn't necessary. It adds all the ERB::Util methods to the current class, which usually isn't desired and can cause unexpected side effects (if you had another h method for example). Instead just access the h method (or other helpers) using the ERB::Util class:

ERB.new("<%= ERB::Util.h @person_name %>").result

查看更多
登录 后发表回答