簡體   English   中英

使用Handlebars.js渲染本地模板

[英]Rendering local templates using Handlebars.js



我剛剛開始使用handlebars.js,試圖擺脫使用字符串concat和injection的丑陋方式呈現動態數據。 我正在嘗試將模板腳本與主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調用)時,模板呈現就很好。

任何人都可以闡明為什么會發生這種情況以及如何解決此問題嗎?

提前致謝。

我設法通過更改此方法解決了該問題:

<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.4/handlebars.min.js"></script>

對此:

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>

謝謝所有的建議。

車把不是問題。 您的網址有問題(如錯誤提示所示); 我注意到您使用的是相對路徑

templates/requests.html

在AJAX請求中。 如果您改用絕對URL( /templates/requests.html ),是否可以解決問題?

同樣,您使用的任何后端服務器是否都配置為提供該目錄?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM