yield in ERB without rails

前端 未结 6 1741
轮回少年
轮回少年 2020-12-30 05:49

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 wit

6条回答
  •  半阙折子戏
    2020-12-30 06:10

    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.

提交回复
热议问题