gpt4 book ai didi

ruby - 将一个 erb 文件包含到另一个文件中

转载 作者:数据小太阳 更新时间:2023-10-29 06:26:47 24 4
gpt4 key购买 nike

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

不过我遇到了一个非常烦人的问题:我无法成功地将一个 .erb 文件包含到另一个文件中。

具体来说,我正在尝试做这样的事情(在伪代码中):

<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 文件,它是从应用程序逻辑中调用的。

我这样做是为了让我的样式表远离主模板,以便更轻松/更清晰地维护应用程序。不过,最终产品(报告)需要是一个独立的 HTML 文件,没有依赖项,因此,我想在生成报告时将这些样式表内联到文档头部。

这看起来应该很容易,但过去一个小时我一直在用头撞墙(谷歌搜索和 RTMF'ing),我一点运气都没有。

这应该如何完成?谢谢。

最佳答案

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

<%= 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:

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

home.css.erb:

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

产生:

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

关于ruby - 将一个 erb 文件包含到另一个文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10236049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com