如何使.html.erb文件在Rails之外工作?

时间:2014-07-19 19:49:43

标签: html ruby erb

我想创建嵌入了Ruby代码的HTML文件,但Ruby On Rails对我的页面来说太过分了。我试过简单地给我的文件' .html.erb'像这样扩展和嵌入ruby:

<%= 2+3 %>,

但它没有用。我想我也必须安装&#39; erb&#39;宝石,但在哪里?如何在没有Rails的情况下使嵌入式Ruby工作?

1 个答案:

答案 0 :(得分:9)

将文件创建为

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

然后

#test.rb
require 'erb'

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

非常好的文档是ERB::new。您不需要安装它,因为它随Ruby安装一起提供。但它位于标准库中,因此您需要在需要时使用它。还有一个例子: -

#test.rb
require 'erb'

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

然后

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

让我们运行fie: -

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