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);
});
});
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: "张三" });
});
模板语法
(太多了,只列举部分,其余的按需看官网文档)
数据
{
name: "张三",
person: {
firstname: "Yehuda",
lastname: "Katz",
},
people: ["Yehuda Katz", "Alan Johnson"],
chars: "& < > \" ' ` =",
isOk: false,
}
模板