Including one erb file into another

前端 未结 4 761
悲&欢浪女
悲&欢浪女 2020-12-08 07:41

I\'m writing a command-line tool that will ultimately output an HTML report. The tool is written in Ruby. (I am not using Rails). I\'m trying to keep the logic of the applic

4条回答
  •  既然无缘
    2020-12-08 07:50

    ERB templates can be nested by evaluating the sub-template from within <%= %> of the main template.

    <%= ERB.new(sub_template_content).result(binding) %>
    

    For example:

    require "erb"
    
    class Page
      def initialize title, color
        @title = title
        @color = color
      end
    
      def render path
        content = File.read(File.expand_path(path))
        t = ERB.new(content)
        t.result(binding)
      end
    end
    
    page = Page.new("Home", "#CCCCCC")
    puts page.render("home.html.erb")
    

    home.html.erb:

    <%= @title %>
    
      
    
    

    home.css.erb:

    body {
      background-color: <%= @color %>;
    }
    

    produces:

    Home
    
      
    
    

提交回复
热议问题