将一个erb文件包含到另一个文件中 [英] Including one erb file into another

查看:92
本文介绍了将一个erb文件包含到另一个文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个命令行工具,该工具最终将输出HTML报告。该工具是用Ruby编写的。 (我没有使用Rails)。我试图将应用程序的逻辑保留在一组文件中,并将HTML模板(.erb文件)保留在另一组文件中。

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 application in one set of files, and the HTML templates (the .erb files) in another set.

但是,这确实是一个令人讨厌的问题:我无法成功地将一个.erb文件包含到另一个文件中。

I'm having a really annoying problem though: I can't successfully include one .erb file into another.

具体来说,我正在尝试执行以下操作(伪-code):

To be specific, I'm trying to do something like this (in pseudo-code):

<html>
<head>
  <style type='text/css'>
    [include a stylesheet here]
    [and another one here]
  </style>
</head>
<body>
  <p>The rest of my document follows...

该示例代码段为本身一个erb文件,该文件正在应用程序逻辑中被调用。

That example snippet is itself an erb file, which is being invoked from within the application logic.

我这样做是为了保持样式表脱离主模板,以使其更容易/更清洁地维护应用程序。但是,最终产品(报告)需要是一个没有依赖性的单个独立HTML文件,因此,我想在生成报告时将这些样式表内联到文档头中。

I'm doing things this way so I can keep my stylesheets out of the main template to make it easier/cleaner to maintain the application. The end product (the report), though, needs to be a single, stand-alone HTML file which has no dependencies, and thus, I want to inline those stylesheets into the document head when the report is generated.

这似乎应该很容易,但是我在过去的一个小时里一直把头撞在墙上(还有Googling和RTMF'ing),但我没有

This seems like this should be easy, but I've been banging my head against a wall (and Googling, and RTMF'ing) for the last hour, and I'm not having any luck at all.

应该怎么做?谢谢。

推荐答案

可以通过在主模板的<%=%>中评估子模板来嵌套ERB模板

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

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

例如:

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:

home.html.erb:

<title><%= @title %></title>
<head>
  <style type="text/css">
<%= render "home.css.erb" %>
  </style>
</head>

home.css.erb:

home.css.erb:

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

产生:

<title>Home</title>
<head>
  <style type="text/css">
body {
  background-color: #CCCCCC;
}
  </style>
</head>

这篇关于将一个erb文件包含到另一个文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆