是否有相当于 Jades 的 Handlbars 扩展

use*_*468 3 express handlebars.js pug

我正在考虑将我的 express 应用程序的诱人语言从 Jade 移至 Handlbars,我想知道是否有与把手中的 Jade 扩展指令等效的指令。

Mat*_*oni 7

正如我所看到的,在handlebars 的存储库中告诉你存在一个handlebars 的依赖,它可以让你扩展块。您可以在此处此处找到更多信息。

布局.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>&copy; 2013</small>
            {{/block}}
        </div>
    </div>

    {{#block "foot"}}
        <script src="assets/js/controllers/home.js"></script> 
    {{/block}}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

在这里,我们定义了一个基本布局,您可以从中扩展其他 html。

页面.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}}
Run Code Online (Sandbox Code Playgroud)

在此文件中,您设置了要从布局扩展的所有数据。

.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'
    ]
});
Run Code Online (Sandbox Code Playgroud)

1. 需要handlebarshandlebars-layout
2. 在handlebar 中注册helper 作为布局。
3. 注册部分将文件设置layout.hbs为名为“layout”的“模块”,然后在 page.html 中设置来自“layout”的扩展名 4. 在模板中编译扩展名page.html
5.渲染模板将数据从js传递到文件。