【发布时间】:2016-01-07 16:22:18
【问题描述】:
我正在考虑将我的 express 应用程序的临时语言从 Jade 转移到 Handlbars,我想知道是否有与 Handlbars 中的 Jade 扩展指令等效的指令。
【问题讨论】:
标签: express handlebars.js pug
我正在考虑将我的 express 应用程序的临时语言从 Jade 转移到 Handlbars,我想知道是否有与 Handlbars 中的 Jade 扩展指令等效的指令。
【问题讨论】:
标签: express handlebars.js pug
正如我所看到的,在车把存储库中告诉您存在对车把的依赖项,可以使您能够扩展块。您可以在here 和here 找到更多信息。
layout.hbs
<!doctype html>
<html lang="en-us">
<head>
{{#block "head"}}
<title>{{title}}</title>
<link rel="stylesheet" href="assets/css/screen.css" />
{{/block}}
</head>
<body>
<div class="site">
<div class="site-hd" role="banner">
{{#block "header"}}
<h1>{{title}}</h1>
{{/block}}
</div>
<div class="site-bd" role="main">
{{#block "body"}}
<h2>Hello World</h2>
{{/block}}
</div>
<div class="site-ft" role="contentinfo">
{{#block "footer"}}
<small>© 2013</small>
{{/block}}
</div>
</div>
{{#block "foot"}}
<script src="assets/js/controllers/home.js"></script>
{{/block}}
</body>
</html>
在这里,我们定义了一个基本布局,您可以在其中扩展其他 html。
page.html
{{#extend "layout"}}
{{#content "head" mode="append"}}
<link rel="stylesheet" href="assets/css/home.css" />
{{/content}}
{{#content "body"}}
<h2>Welcome Home</h2>
<ul>
{{#items}}
<li>{{.}}</li>
{{/items}}
</ul>
{{/content}}
{{#content "foot" mode="prepend"}}
<script src="assets/js/analytics.js"></script>
{{/content}}
{{/extend}}
在此文件中,您设置要从布局扩展的所有数据。
.js 文件
var handlebars = require('handlebars');
var layouts = require('handlebars-layouts');
// Register helpers
handlebars.registerHelper(layouts(handlebars));
// Register partials
handlebars.registerPartial('layout', fs.readFileSync('layout.hbs', 'utf8'));
// Compile template
var template = handlebars.compile(fs.readFileSync('page.html', 'utf8'));
// Render template
var output = template({
title: 'Layout Test',
items: [
'apple',
'orange',
'banana'
]
});
1。需要 handlebars 和 handlebars-layout
2.将handlebar中的helper注册为布局。
3.注册partials将文件layout.hbs设置为一个名为'layout'的“模块”,然后在page.html中设置'layout'的扩展名
4. 在模板中编译扩展page.html。
5. 渲染模板将数据从 js 传递到文件。
【讨论】:
对于那些正在寻找 webpack 解决方案的人。我在配置中留下了一段 sn-p 代码:
webpack.config.js
...
const fs = require("fs")
const HandlebarsPlugin = require("handlebars-webpack-plugin")
const HandlebarsLayouts = require('handlebars-layouts');
module.exports = {
...,
plugins: [
...,
new HandlebarsPlugin({
...,
onBeforeSetup: function(Handlebars){
Handlebars.registerHelper(HandlebarsLayouts(Handlebars));
Handlebars.registerPartial('default', fs.readFileSync('path/to/layout.hbs', 'utf8'));
}
})
]
}
参考资料:
【讨论】: