绑定数据JS



我想将数据绑定到{{}}胡子模板。

这里的代码:

<div id="app">
<h1>An Introduction to {{book}}</h1>
<div>
<p>
{{book}} is a series of fantasy novels written by British author {{author}}.
</p>
</div>

<table id="hogwarts">
<caption>{{school}} Student Table</caption>
<tr>
<th>ID</th>
<th>Name</th>
<th>Gender</th>
</tr>
<tr>
<td>{{harry.id}}</td>
<td>{{harry.name}}</td>
<td>{{harry.gender}}</td>
</tr>
<tr>
<td>{{hermione.id}}</td>
<td>{{hermione.name}}</td>
<td>{{hermione.gender}}</td>
</tr>
</table>
</div>
<!-- DO NOT change anything within <div id="app"> tag -->
<div>
The central character in the series is {{harry.name}}, ...
</div>

脚本如下所示:

<script>
//data you need
let data = {
book: "Harry Potter",
school: "Hogwarts School of Witchcraft and Wizardry",
antagonist: "Lord Voldemort",
harry: {id: "1", name: "Harry Potter", gender: "M"},
ron: {id: "2", name: "Ron Weasley", gender: "M"},
hermione: {id: "3", name: "Hermione Granger", gender: "F"},
author: "JK Rowling",
};
//Implement this bind function
function bind(data) {
// write code here
}
//invoke the function
bind(data);
</script>

这就是我目前所做的:

function bind(data) {

var template = document.getElementById("app").innerHTML;
var html = Mustache.render(template,data);
// console.log(template);
// console.log(html);

var app = document.querySelector("#app");

app.innerHTML = html; 
var div = document.querySelectorAll("div")[2].innerHTML; 
var html2 = Mustache.render(div,data);
// console.log(div);

document.querySelectorAll("div")[2].innerHTML = html2; 
}

但它不满足只允许在没有框架的情况下使用纯JS的要求(我使用的是胡子库(任何人帮我,谢谢

由于您没有任何复杂的表达式,因此创建自己的模板并不困难。我们可以使用String.prototype.replace,它将帮助我们走很长的路。

const renderTemplate = function(template, data) {
// use regex to extract {{templates}} and replace the values
return template.replace(/{{[w.]+}}/g, function(s) {
const expr = s.substring(2, s.length - 2); // remove "{{" and "}}"
const sections = expr.split(".");
const val = sections.reduce((prev, cur) => prev[cur], data); // loop through nested object call and access values
return val; // return the replacement
});
}

我们可以这样使用它:

const data = {
person: {
name: "John",
age: 35
}
};
const result = renderTemplate("<p>{{person.name}} is {{person.age}} years old.</p>", data);
// ^ "<p>John is 35 years old</p>"

最新更新