当前位置:网站首页>Handlebars.js模版引擎用法一
Handlebars.js模版引擎用法一
2022-06-09 12:04:00 【别盯着我的名字看】
一、为什么要使用Handlebars模版引擎
1、Handlebars是全球使用率最高的模板引擎,所以当之无愧是全球最受欢迎的模板引擎.Handlebars在许多前端框架中都被引入,比如在MUI和AmazeUI等框架,都推荐使用Handlebars。
2、可维护性(后期改起来方便);可扩展性(想要增加功能,增加需求方便);开发效率提高(程序逻辑组织更好,调试方便);看起来方便。
3、Handlebars基本语法极其简单,使用{{value}}将数据包装起来即可,Handlebars会自动匹配响应的数值和对象,容易上手。
二、怎么使用Handlebars
1、先获取handlebars
通过Handlebars官网下载:http://handlebarsjs.com./installation.html ; 通过npm下载:npm install –save handlebars ; 通过bower下载:bower install –save handlebars ; 通过github下载:https://github.com/daaain/Handlebars.git ;
2、基本用法
⑴.引入handlebars到项目中
<script src="js/handlebars-v4.0.11.js"></script>⑵.在script标签里写模板内容
这儿的标签type=”text/x-handlebars-template” 且需要设置一个id
<script id="card-template" type="text/x-handlebars-template">
<!--再这儿写相关内容-->
</script>⑶.在JS中编译模版
var t = $("#card-template").html(); //得到模版中的html
var f = Handlebars.compile(t);//预编译模版
var h = f(data); //将数据放入模板中
$("#card").html(h); //显示在某一个标签里面三、简单的例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.card {
font-size: 24px;
margin: 20px;
padding: 10px;
float: left;
background: #5cffeb;
}
</style>
</head>
<body>
<div class="card" id="card"></div>
<script src="js/jquery-2.1.1.js"></script>
<script src="js/handlebars-v4.0.11.js"></script>
<script id="card-template" type="text/x-handlebars-template">
<div>姓名:{{name}}</div>
<div>年龄:{{age}}</div>
<div>出生地:{{home}}</div>
<div>职业:{{job}}</div>
</script>
<script>
var data = {
name: "自酌一杯酒",
age: 22,
home: "中国",
job: "WEB前端工程师"
};
var t = $("#card-template").html(); //得到模版中的html
var f = Handlebars.compile(t);//预编译模版
var h = f(data); //将数据放入模板中
$("#card").html(h); //显示在某一个标签里面
</script>
</body>
</html>虽然感觉这个简单的例子,比起之前在js里用拼接的方法看起稍麻烦点。但如果在js里写更多的html代码呢,这样不方便维护。并且handlebars的魅力还有很多.
边栏推荐
猜你喜欢

"Forget to learn again" shell Basics - 28. Description of conditional expressions in awk

Endnote | how to quickly share literature with others (including title + Notes +pdf file) | endnote save backup

Basic image transformation in gdi+

BFS练手题目

Software project management

JMeter installation tutorial
LeetCode-732. My schedule III, differential array

flutter Dio示例

ep240--leding

How does PostgreSQL speed up the recovery of transaction IDS through the vacuum
随机推荐
GaussDB(for Redis)新特性发布:前缀搜索千倍提升与集群版多租隔离
使 QComboBox 下拉一个树形结构列表
Golang-RPC(七):如何调试gRPC服务
[STM32] Hal library CRC verification
MySQL optimistic lock, pessimistic lock and multi granularity lock
LeetCode-732. 我的日程安排表 III,差分数组
ORM框架简介和常用ORM框架
【STM32】GuiLite基于HAL库的移植
Golang access pin notification
kolla-ansible openstack登录 证书不可用
[nick] 精读知识
C#/VB.NET 在PDF表格中添加条形码
Gamefi's new departure, aquanee will log in to gate and bitmart on June 9
直播预告|数据库沙龙—【开源生态专场】
Redis data structure and introduction
Cubase pro 12
Comment on "8 reasons why developers don't like low code and no code"
【论文写作】AI会议引用格式、出版地、出版社
Rédaction de documents scientifiques
似然函数的意义