Underscore.js模板:模板变量未渲染

3
我刚开始尝试使用jQuery和underscore.js来掌握JavaScript单页应用程序开发的基础知识。在涉及任何客户端MVC框架之前,我想先了解一些更基本的内容,例如模板插入。
我的问题是:当HTML通过_.template()渲染时,模板变量不会被评估。HTML代码如下:
<body>
    <script id="app-view-1" type="text/template">
      <div id="app-view-1-container" class="app-workbench-container active-panel">
        <h2><%= title =></h2>
        <ul class="choice-list">
          <li><a class="" id="" href="#" data-choice="choice 1"></a></li>
          <li><a class="" id="" href="#" data-choice="choice 2"></a></li>
        </ul>
      </div>
    </script>

    <script id="app-view-2" type="text/template">
      <div id="app-view-2-container" class="app-workbench-container active-panel">
        <h2><%= title =></h2>
        <form id="" class="input-panel active-panel" action="#">
          <input type="text" id="input-field-1" class="app-control">
          <input type="radio" id="radio-button-1" class="app-control" value="value-1">Value 1
          <input type="submit" id="submit-button-1" class="app-control">
        </form>
      </div>
    </script>

    <header id="app-header">
      <h1>Single Page App (SPA) Test</h1>
      <nav id="main-menu-panel">
        <ul id="main-menu">
          <li class="main-menu-item"><a id="view-1" class="" data-target="app-view-1" href="#">View 1</a></li>
          <li class="main-menu-item"><a id="view-2" class="" data-target="app-view-2" href="#">View 2</a></li>
          <li class="main-menu-item"><a id="view-3" class="" data-target="app-view-3" href="#">View 3</a></li>
        </ul>
      </nav>
    </header>

    <main id="app-body">
      <p class="active-panel">Different app partials come here...</p>
    </main>

    <footer></footer>

    <script src="js/vendors/jquery/jquery-1.10.2.min.js"></script>
    <script src="js/vendors/node_modules/underscore/underscore-min.js"></script>
    <script src="js/app.js"></script>

  </body>

这是app.js的JavaScript代码:

$(document).ready(function(){
  console.log("Application ready...\n");
  $(".main-menu-item").on("click", "a", function(event){
    var target = $(this).data("target");
    var partial = _.template($("#" + target).html());
    event.preventDefault();
    $(".active-panel").remove();
    $("#app-body").append(partial({title : target}));
  });
});

然而,在渲染的输出中,"<%= title =>" 出现为字面字符串,应该在 partial() 函数中分配的实际标题没有出现。出了什么问题?任何帮助都将不胜感激。
1个回答

9
你的模板有误。你使用了<%= ... =>,正确应该是<%= ... %>
根据underscore文档提供的信息,他们提供了以下示例。
var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'}); // returns "hello: moe"

支持的underscore.js模板标签包括:
  • <% ... %>用于脚本执行
  • <%= ... %>用于插值变量(打印)
  • <%- ... %>用于插值变量并进行HTML转义
编辑:

我使用了这个jsFiddle。将来请提供类似的示例,这对每个人都会更容易。 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接