kjf*_*tch 5 html haml templates
我正在使用Haml(Haml/Sass 3.0.9 - Classy Cassidy)独立生成静态HTML.我想创建一个共享布局模板,我的所有其他模板都继承该模板.
Layout.haml
%html
%head
%title Test Template
%body
.Content
Run Code Online (Sandbox Code Playgroud)
Content.haml
SOMEHOW INHERIT Layout.haml
SOMEHOW Change the title of the page "My Content".
%p This is my content
Run Code Online (Sandbox Code Playgroud)
生产:
Content.html
<html>
<head>
<title>My Content</title>
</head>
<body>
<div class="Content">
<p>This is my content</p>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
但这似乎不太可能.我已经看到在使用带有Rails的Haml时使用渲染部分,但在使用Haml独立时无法找到任何解决方案.
必须将布局代码放在我的所有模板中都是一个维护噩梦; 所以我的问题是如何避免这样做?有没有一种标准的方法可以解决这个问题?我错过了什么基本的东西?
我发现了一个类似的问题:在Rails的HAMLoutside中渲染HAML部分
我创建了一个可以满足我需要的原型。我只需要将其创建为模块,并允许它接受布局模板和内容模板作为参数(以及数据集)。
require "haml"
layoutTemplate = File.read('layout.haml')
layoutEngine = Haml::Engine.new(layoutTemplate)
layoutScope = Object.new
output = layoutEngine.render(scope=layoutScope) { |x|
case x
when :title
scope.instance_variable_get("@haml_buffer").buffer << "My Title\n"
when :content
contentTemplate = File.read('page.haml')
contentEngine = Haml::Engine.new(contentTemplate)
contentOutput = contentEngine.render
scope.instance_variable_get("@haml_buffer").buffer << contentOutput
end
}
puts output
Run Code Online (Sandbox Code Playgroud)
布局.haml
%html
%head
%title
- yield :title
%body
.content
- yield :content
Run Code Online (Sandbox Code Playgroud)
页面.haml
%h1 Testing
%p This is my test page.
Run Code Online (Sandbox Code Playgroud)
输出
<html>
<head>
<title>
My Title
</title>
</head>
<body>
<div class='content'>
<h1>Testing</h1>
<p>This is my test page.</p>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)