Calling ERB without Rails: undefined method 'raw'

筅森魡賤 提交于 2019-12-23 09:22:53

问题


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?


回答1:


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;" 



回答2:


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



来源:https://stackoverflow.com/questions/7950463/calling-erb-without-rails-undefined-method-raw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!