- Objective:
- Breadcrumb:
# 概念阐释
## 语义
Handlebars是[[Ajax]]库中的一种文件。
## 语法
### 在html中引入handlebars库文件
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.js"></script>
```
- `cdnjs.cloudflare.com`: 这是服务器的域名。通过CloudFlare的CDN功能实现物理距离最近的库文件调用,优化加载时间。
- `/ajax/`(全称为Asynchronous JavaScript and XML)是一种允许服务器请求数据-加载数据,但不刷新整个页面的技术,提高了用户体验。
- `/ajax/libs/handlebars.js/4.0.11/`: 这是服务器上资源的路径。它指向的是Handlebars.js库的一个特定版本(4.0.11)
- `handlebars.js`: 这是具体的文件名。
总结:使用[[CDN 内容分发网络]],AJAX可以大大提高页面加载速度,提升用户体验。使用js库文件可提高编程效率。也可以将文件下载到本地。
```
<script src="handlebars.min.js"></script>
```
### HTML的`<head>`中编辑要嵌入`<body>`的内容:
```html
<script id="ice-cream" type="text/x-handlebars-template">
<h2>Why {{flavor}} is the best</h2>
<p>
It is without a doubt that {{flavor}} is the best ice cream flavor in the world. If it was left to me, I would have {{flavor}} ice cream all year round. The next time I get ice cream, I will be getting {{flavor}} because why get something else when when you can get the best.
</p>
</script>
```
- `<script>` 标签内通常用于插入或引用JavaScript代码,但在这种情况下,它被用于定义一个Handlebars模板。
- `id="ice-cream"` 是该元素的ID属性,用于在JavaScript中引用这个模板。
- `type="text/x-handlebars-template"` 属性告诉浏览器这是一个Handlebars模板,而不是普通的JavaScript代码。这个类型值意味着浏览器不会试图执行这个脚本,但你可以在JavaScript中使用document.getElementById()来找到这个模板并使用Handlebars库进行处理。
- **`{{}}`** 是要被替换的内容,不仅是`text`,也可以是属性值`class`;
#### 结尾引用main.js本地文件
```html
<script src="public/main.js" type="text/javascript"></script>
```
- `type="text/javascript"`: `type`属性定义了嵌入内容的MIME类型。在这种情况下,它表明这是一个JavaScript文件。
### 在main.js中创建js代码:
1. 访问并修改handlebar元素的资源
```js
const source = document.getElementById('ice-cream').innerHTML;
```
2. 调用Handlebars.compile**模板函数**,参数为source
```js
const template = Handlebars.compile(source);
```
3. 添加需要修改的内容的[[JavaScript 对象]]
```js
const context = {
flavor: 'chocolate'
};
```
4. 模板函数添加context参数
```js
const compiledHTML = template(context);
```
5. 访问要填充的HTML元素
```js
const fill = document.getElementById('scream');
```
6. 将handlhandlebar的内容添加到访问元素上
```js
fill.innerHTML = compiledHTML;
```
# 实例
# 相关内容
# 问题
- [练习题](https://www.codecademy.com/courses/build-interactive-websites/lessons/learn-handlebars/exercises/handlebars-expression)
🌟🌟
- 用handlebar创建一个可替换的greeting,并添加到HTML的`hello` ID下。
- 如何修改`p`的样式?
# 问题答案
```js
const source = document.getElementById('greet').innerHTML;
const template = Handlerbars.compile(source);
const context = {
greeting: 'string hello world'//gretting是Handlebars expression,HTML中可替换的{{}}内容
}
const compileHTML = template(context);
const fill = document.getElementById('hello');
fill.innerHTML = compileHTML;
```
# 参考资料
- [codecademy-Introduction to Handlebars](https://www.codecademy.com/courses/build-interactive-websites/lessons/learn-handlebars/exercises/handlebars-intro)