【发布时间】:2023-03-24 13:25:02
【问题描述】:
我刚刚开始使用 handlebars.js,试图摆脱使用字符串连接和注入的丑陋方式呈现动态数据。我正在尝试将模板脚本与主 HTML 文件分开,并通过函数调用呈现模板文件。
这是我所拥有的:
script.js
----------
$(function() {
var myData = { requests: [
{id: "1", firstname: "Roger", lastname: "Jones", age: 24},
{id: "2", firstname: "Phillip", lastname: "Green", age: 44}
]};
$.ajax({
url: 'templates/requests.html',
dataType: 'html',
cache: false,
success: function(data, status, response) {
var template = Handlebars.compile(response.responseText);
var context = myData;
$('#InjectTemplate_Requests').html(template(context));
}
});
});
index.html
-------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Handlebars</title>
</head>
<body>
<div id="InjectTemplate_Requests">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.4/handlebars.min.js"></script>
<script src="script.js"></script>
</body>
</html>
requests.html (template file inside the 'templates' directory)
--------------
<table>
<thead>
<th>Name</th>
<th>Status</th>
<th>Type</th>
</thead>
<tbody>
{{#requests}}
<tr>
<td>{{firstname}} {{lastname}}</td>
<td>{{age}}</td>
</tr>
{{/requests}}
</tbody>
</table>
File Structure
--------------
index.html
|
script.js
|
|
|---templates
|
|
|---requests.html
我似乎在控制台上收到此错误:Failed to load resource: The requested URL was not found on this server. 但是,当我将模板添加到Index.html(并从脚本文件中删除 ajax 调用)时,模板呈现得很好。
谁能解释为什么会发生这种情况以及我该如何解决这个问题?
提前致谢。
【问题讨论】:
-
我们不知道您的目录结构是什么才能告诉您为什么会收到 404。请记住,路径是相对于发出请求的页面的 url 路径
-
对不起,我犯的愚蠢错误。我会修改的,谢谢。
-
在没有解析器“修复”的情况下,您能否在 html 响应中的 TR 和 TBODY 标记之间有垃圾?
-
@dandavis 在变成 DOM 元素之前它只是一个字符串。模板编译会改变这一点
-
哇!错过了“responseText”部分... nvrmnd.
标签: javascript handlebars.js template-engine