学习Handlebars,从这里开始!

站长
· 阅读数 10
一、Handlebars 是什么?
Handlebars 是一个页面模板化工具。
1、使用场景
当网站中很多页面的排版格式是相同的,只是其中内容不同,此工具就是比较好的解决方案。更多使用建议,看这里!
二、怎么使用?
1、远程handlebars
通过加载 远程handlebars库,解析页面模板并加载到HTML中。通过下面5个步骤清晰展示 handlebars 怎么加载和使用。负责下面代码到 index.html 中,再用浏览器打开 index.html 即可看到效果。
<!DOCTYPE html>
<html lang='zh-CN'>
<head>
<meta charset="utf-8">
<title>学习 Handlebars </title>
<!-- 1、加载 handlebars 库 -->
<script src="https://cdn.jsdelivr.net/npm/handlebars@latest/dist/handlebars.js"></script>
<script>
// 2、页面加载时,调用下面代码
document.addEventListener("DOMContentLoaded", function () {
const article = `
<h1>{{title}}</h1>
<h3>{{description}}</h3>
<p>{{detail}}</p>
`
const data = { title: "第一篇文章", description: "简要", detail: "详细内容" };
// 3、调用 handlebars 解析模板
var template = Handlebars.compile(article);
// 4、加载数据到模板中,并创建元素
var root = document.createElement("div");
root.innerHTML = template(data);
// 5、显示在页面中
document.body.appendChild(root);
});
</script>
</head>
<body>
</body>
</html>
2、webpack 中使用 handlebars
如果远程handlebars库不能用,会影响到项目,所以下载 handlebars 库到本地。具体使用步骤如下:
# 1、初始化 webpack 项目
mkdir learn-webpack
cd learn-webpack
npx webpack-cli init
# 2、安装下面选项选择
? Which of the following JS solutions do you want to use? ES6
? Do you want to use webpack-dev-server? No
? Do you want to simplify the creation of HTML files for your bundle? Yes
? Do you want to add PWA support? No
? Which of the following CSS solutions do you want to use? none
? Do you like to install prettier to format generated configuration? No
? Pick a package manager: npm
# 3、安装 handlebars 和 loader
npm install handlebars handlebars-loader
- 增加 webpack.config.js 文件中 rules 项,把 handlebars-loader 加进去。
module: {
rules: [
{
test: /\.hbs$/,
loader: "handlebars-loader"
}
],
},
- 创建模板文件:src/article.hbs,代码如下:
<h1>{{title}}</h1>
<h3>{{description}}</h3>
<p>{{detail}}</p>
- 修改 src/index.js,代码如下:
// 1、页面加载时,调用下面代码
document.addEventListener("DOMContentLoaded", function () {
// 2、加载 handlerbars 模板
const article = require("./article.hbs");
// 3、定义模板需要的数据
const data = { title: "第一篇文章", description: "简要", detail: "详细内容" };
// 4、加载数据到模板中,并创建元素
var root = document.createElement("div");
root.innerHTML = article(data);
// 5、显示在页面中
document.body.appendChild(root);
});
- 修改 index.html,加载 src/index.js 代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Webpack App</title>
<script src="./src/index.js"></script>
</head>
<body>
</body>
</html>
# 8、运行
npm run build
最后用浏览器打开 dist/index.html
看效果。
三、其他集成工具
1、handlebars-webpack-plugin
使用 Handlebars 构建你的静态 HTML 页面。更多内容,看这里!
2、babel-plugin-handlebars-inline-precompile
把字符串表示的 Handlebars 模板,用在 JavaScript 代码中。
import hbs from "handlebars-inline-precompile";
const compiledTemplate = hbs`{{name}}`;