简体   繁体   English

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

[英]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. 我想创建嵌入了Ruby代码的HTML文件,但是Ruby On Rails对我的页面来说太多了。 I've tried simply giving my file '.html.erb' extension and embedding ruby like this: 我试着简单地给我的文件'.html.erb'扩展名并嵌入红宝石,如下所示:

<%= 2+3 %>,

but it didn't work. 但这没用。 I suppose I also have to install 'erb' gem, but where to? 我想我也必须安装'erb'gem,但是在哪里呢? How do I make embedded Ruby work without Rails? 如何在没有Rails的情况下使嵌入式Ruby正常工作?

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 . 很好的文档是ERB::new You don't need to install it, as it ships with your Ruby installation. 您不需要安装它,因为它随Ruby安装一起提供。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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