yield in ERB without rails

2019-02-04 13:54发布

How can I use yield for template inheritance in erb? I want to use erb in a plain ruby CGI script and want to use a base template and subtemplate like it Rails with the application template does.

5条回答
我命由我不由天
2楼-- · 2019-02-04 14:35

I wrote about adding this to the Standard Library's ERB here http://hostiledeveloper.com/2015/05/28/working-with-templates-in-ruby-erb.html

It's surprisingly a pain in the butt.

查看更多
聊天终结者
3楼-- · 2019-02-04 14:43

You can use Tilt but if you don't want to add an extra dependency, here's a better example on how you can yield in erb:

require "erb"

class Controller
  TEMPLATE = ERB.new("Hello <%= @someone %>\n\n<%= yield %>")

  def initialize(someone)
    @someone = someone
  end

  def render
    TEMPLATE.result(self.get_binding { yield })
  end

  def get_binding
    binding
  end
end

puts Controller.new("World").render { "I'm Jack" }
# =>
Hello World

I'm Jack

I found the answer here.

查看更多
干净又极端
4楼-- · 2019-02-04 14:44

I don't think you can - Rails provides that infrastructure as part of actionpack.

What you may be able to do is take actionpack and add it into your script.

Alternatively you could roll a lightweight templating system yourself.

Alternatively alternatively use Rails or Merb or Sinatra.

查看更多
劳资没心,怎么记你
5楼-- · 2019-02-04 14:47
def a
  ERB.new('<%= yield %>').result(binding)
end
a{123}
#=> "123"

It's important that the call to Kernel#binding be inside a method, that way the context includes the block (ERB#result won't take a block).

查看更多
Luminary・发光体
6楼-- · 2019-02-04 14:53

Check out Tilt (http://github.com/rtomayko/tilt/). It's the gem that handles templating in Sinatra and it provides ERB yields along with many other nice features.

查看更多
登录 后发表回答