【问题标题】:How to make .html.erb file work outside of Rails?如何使 .html.erb 文件在 Rails 之外工作?
【发布时间】:2014-07-19 19:49:43
【问题描述】:

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

<%= 2+3 %>,

但它没有用。我想我还必须安装“erb”gem,但是在哪里呢?如何在没有 Rails 的情况下使嵌入式 Ruby 工作?

【问题讨论】:

  • erubis,这是 Rails 用于 ERB 的。
  • 您在什么环境下工作?你说你没有rails - 你用什么来服务页面?辛纳特拉?杰基尔?其他环境?
  • @dpassage,我不想使用除了 html 之外的任何东西,里面有 ruby​​。
  • @lakesare 假设您希望人们在互联网上看到这些 html 文件,您将需要运行某种带有 erb 插件的网络服务器。

标签: html ruby erb


【解决方案1】:

将您的文件创建为

#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>

让我们开始吧:-

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

【讨论】:

  • 谢谢,还有一个问题:我现在如何启动本地服务器来执行这些文件?这些能在heroku上工作吗?
  • 创建一个config/initializers/myfile.rb,不知道heroku
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-21
  • 1970-01-01
  • 2014-08-24
  • 2013-11-30
  • 2011-04-23
  • 1970-01-01
相关资源
最近更新 更多