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

lak*_*are 1 html ruby erb

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

<%= 2+3 %>,
Run Code Online (Sandbox Code Playgroud)

但它不起作用.我想我也必须安装'erb'宝石,但在哪里?如何在没有Rails的情况下使嵌入式Ruby工作?

Aru*_*hit 9

创建您的文件

#test.html.erb
<%= 2 + 3 %>
Run Code Online (Sandbox Code Playgroud)

然后

#test.rb
require 'erb'

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

非常好的文档是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
Run Code Online (Sandbox Code Playgroud)

然后

#test.html.erb
<table>
  <% @fruits.each do |fruit| %>
    <tr> <%= fruit %> </tr>
  <% end %>
</table>
Run Code Online (Sandbox Code Playgroud)

让我们跑吧: -

arup@linux-wzza:~/Ruby> ruby test.rb
<table>
      <tr> apple </tr>
      <tr> orange </tr>
      <tr> banana </tr>
  </table>
arup@linux-wzza:~/Ruby>
Run Code Online (Sandbox Code Playgroud)