简体   繁体   中英

How to make .html.erb file work outside of Rails?

I want to create HTML file with Ruby code embedded in it, but Ruby On Rails is too much for my page. I've tried simply giving my file '.html.erb' extension and embedding ruby like this:

<%= 2+3 %>,

but it didn't work. I suppose I also have to install 'erb' gem, but where to? How do I make embedded Ruby work without Rails?

Create your file as

#test.html.erb
<%= 2 + 3 %>

then

#test.rb
require 'erb'

erb = ERB.new(File.open("#{__dir__}/test.html.erb").read)
puts erb.result # => 5

Very good documentation is ERB::new . You don't need to install it, as it ships with your Ruby installation. But it is in standard library , so you need to require it, when you need it. One more example :-

#test.rb
require 'erb'

@fruits = %w(apple orange banana)
erb = ERB.new(File.open("#{__dir__}/test.html.erb").read, 0, '>')
puts erb.result binding

and then

#test.html.erb
<table>
  <% @fruits.each do |fruit| %>
    <tr> <%= fruit %> </tr>
  <% end %>
</table>

Lets run the fie :-

arup@linux-wzza:~/Ruby> ruby test.rb
<table>
      <tr> apple </tr>
      <tr> orange </tr>
      <tr> banana </tr>
  </table>
arup@linux-wzza:~/Ruby>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM