Including one erb file into another

前端 未结 4 762
悲&欢浪女
悲&欢浪女 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><%= @title %></title>
    <head>
      <style type="text/css">
    <%= render "home.css.erb" %>
      </style>
    </head>
    

    home.css.erb:

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

    produces:

    <title>Home</title>
    <head>
      <style type="text/css">
    body {
      background-color: #CCCCCC;
    }
      </style>
    </head>
    
    0 讨论(0)
  • 2020-12-08 07:50
    <%= ERB.new(sub_template_content).result(binding) %>
    

    does not work, when you are using erb cli utility, multiple _erbout variables are overriden and only last one is used.

    use it like this:

    <%= ERB.new(sub_template_content, eoutvar='_sub01').result(binding) %>
    
    0 讨论(0)
  • 2020-12-08 07:58

    From within my .erb file, I had to do this:

    <%= ERB.new(File.read('pathToFile/myFile.erb'), nil, nil, '_sub01').result(binding) %>
    

    The other answers in this thread assumed you had a variable with your content in it. This version retrieves the content.

    0 讨论(0)
  • 2020-12-08 08:14

    I'm needing this in a Sinatra app, and I find that I can just call it the same way I called the original:

    In the sinatra app, I call the index:

    erb :index
    

    Then, in the index template, I can do the same for any sub-template:

    <div id="controls">
      <%= erb :controls %>
    

    ..which shows the 'controls.erb' template.

    0 讨论(0)
提交回复
热议问题