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?
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 # => "<script>name</script>"
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