Chr*_*ane 29 ruby erb templating
我正在编写一个最终输出HTML报告的命令行工具.该工具是用Ruby编写的.(我不使用Rails).我试图将应用程序的逻辑保存在一组文件中,并将HTML模板(.erb文件)保存在另一组文件中.
我有一个非常恼人的问题:我无法成功将一个.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...
Run Code Online (Sandbox Code Playgroud)
该示例代码段本身就是一个erb文件,它是从应用程序逻辑中调用的.
我正在这样做,所以我可以将样式表保留在主模板之外,以便更容易/更清洁地维护应用程序.但是,最终产品(报告)需要是一个没有依赖关系的单个独立HTML文件,因此,我希望在生成报告时将这些样式表内联到文档头中.
这看起来应该很容易,但是我在最后一小时一直在撞墙(和谷歌搜索和RTMF),我根本没有运气.
应该怎么做?谢谢.
cyd*_*ser 34
可以通过从主模板的<%=%>内评估子模板来嵌套ERB模板.
<%= ERB.new(sub_template_content).result(binding) %>
Run Code Online (Sandbox Code Playgroud)
例如:
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")
Run Code Online (Sandbox Code Playgroud)
home.html.erb:
<title><%= @title %></title>
<head>
<style type="text/css">
<%= render "home.css.erb" %>
</style>
</head>
Run Code Online (Sandbox Code Playgroud)
home.css.erb:
body {
background-color: <%= @color %>;
}
Run Code Online (Sandbox Code Playgroud)
生产:
<title>Home</title>
<head>
<style type="text/css">
body {
background-color: #CCCCCC;
}
</style>
</head>
Run Code Online (Sandbox Code Playgroud)
Jon*_*ter 16
我在Sinatra应用程序中需要这个,我发现我可以像调用原始文件一样调用它:
在sinatra应用程序中,我称之为索引:
erb :index
Run Code Online (Sandbox Code Playgroud)
然后,在索引模板中,我可以对任何子模板执行相同的操作:
<div id="controls">
<%= erb :controls %>
Run Code Online (Sandbox Code Playgroud)
..which显示'controls.erb'模板.
<%= ERB.new(sub_template_content).result(binding) %>
Run Code Online (Sandbox Code Playgroud)
不起作用,当您使用erb cli实用程序时,会覆盖多个_erbout变量,并且只使用最后一个.
像这样用它:
<%= ERB.new(sub_template_content, eoutvar='_sub01').result(binding) %>
Run Code Online (Sandbox Code Playgroud)
从我的.erb文件中,我必须这样做:
<%= ERB.new(File.read('pathToFile/myFile.erb'), nil, nil, '_sub01').result(binding) %>
Run Code Online (Sandbox Code Playgroud)
这个帖子中的其他答案假设你有一个包含你内容的变量.此版本检索内容.
| 归档时间: |
|
| 查看次数: |
25801 次 |
| 最近记录: |