Handlebars

yuhuo2022-03-28开发库NodeJs库

集成方式

浏览器

<script src="https://cdn.jsdelivr.net/npm/handlebars@latest/dist/handlebars.js"></script>
<script>
    const template = Handlebars.compile("Name: {{ name }}");
    const target = template({ name: "张三" });
</script>

node

安装

npm install handlebars

运行

const Handlebars = require("handlebars");

const template = Handlebars.compile("Name: {{name}}");
const target = template({ name: "张三" });

express

安装

npm install express
npm install hbs

运行

const express = require("express");
const app = express();

// 指定模板引擎
app.set('view engine', 'hbs');
// 指定模板根目录
app.set('views', 'topic/express/views');

app.get("/get", (req, res) => {
    // 渲染并返回HTML代码
    res.render("example/get.hbs", { name: "张三" }, (error, html) => {
        // 错误对象,成功时为null
        console.log(error);
        // 渲染后的HTML
        console.log(html);
    });
});
{{! topic/express/views/example/get.hbs }}
姓名: {{ name }}

koa

安装

npm install koa
npm install koa-views handlebars

运行

const Koa = require("koa");
const views = require("koa-views");

const app = new Koa();

// 指定模板引擎及模板根目录
app.use(
    views("topic/koa/views", {
        map: { hbs: "handlebars" },
    })
);

app.use(async (ctx) => {
    // 渲染并返回HTML代码
    await ctx.render("example/get.hbs", { name: "张三" });
});
{{! topic/koa/views/example/get.hbs }}
姓名: {{ name }}

模板语法

(太多了,只列举部分,其余的按需看官网文档)

数据

{
    name: "张三",
    person: {
        firstname: "Yehuda",
        lastname: "Katz",
    },
    people: ["Yehuda Katz", "Alan Johnson"],
    chars: "& < > \" ' ` =",
    isOk: false,
}

模板

{{! 注释 }}
简单表达式:{{name}}
对象表达式:{{person.firstname}}{{person.lastname}}

原生: {{{chars}}}
转义: {{chars}}

更改上下文:
{{#with person}}
    {{firstname}}
    {{lastname}}
    {{else}}
    空值时显示
{{/with}}
重定义已知引用:
{{#with person.firstname as | fname |}}
    {{fname}}
{{/with}}

遍历数组:
{{#each people}}
    {{@index}}{{this}}
    {{else}}
    空值或空数组时显示
{{/each}}

遍历对象:
{{#each person}}
    {{@key}}{{this}}
    {{else}}
    空值时显示
{{/each}}

条件判断:(只能放单个参数,不能放表达式)
{{#if isOk}}
    true时显示
    {{else}}
    false时显示
{{/if}}

条件判断:(和if相反)
{{#unless isOk}}
    false时显示
{{/unless}}
Last Updated 2024/3/14 09:51:53