尝试使用rack gem和erb提供文件,erb正在渲染的html文件中的css链接标签似乎不起作用:
用于执行erb并渲染视图的helper:
def render(file, *args)
template = File.read("public/#{file}.html.erb") ||
File.read("public/404.html.erb")
template_output = ERB.new(template).result(binding)
res = Rack::Response.new(bind_layout { template_output })
end
def bind_layout(&block)
layout = File.read("public/layout.html.erb")
ERB.new(layout).result(binding)
end
带有 css 导入的布局:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="stylesheets/layout.css">
</head>
<body>
<div class="main">
<h1>ONM LAYOUT</h1>
<%= yield %>
<h2>onfoototer</h2>
</div>
</body>
</html>
页面正确提供模板和布局,但链接的 css 不正确
问题在于,rack 将文件解释为 html,与绑定的 html 视图一起提供服务。我找到的解决方案是使用 Rack::Static 来正确地提供静态 css:
use Rack::Static, :urls => ['/static/stylesheets', 'layout.css']
。