开发者

yield in ERB without rails

H开发者_如何学Cow 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.


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).


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.


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.


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.


app.rb

require 'erb'

class Template
    def render(template_name="base")
        ERB.new(File.read("#{template_name}.erb")).result(binding)
    end
end

result = Template.new.render do
    ERB.new(File.read("index.erb")).result
end

puts result

base.erb

<main>
    <%= render "footer" %>
    <%=yield %>
</main>

index.erb

<h1>Index Page</h1>

footer.erb

<h1>Footer here</h1>

output image:

yield in ERB without rails

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜