Underscore.js模板:未呈现的模板变量

时间:2013-11-20 14:35:11

标签: javascript jquery templates underscore.js single-page-application

我刚刚开始使用jQuery和underscore.js来掌握使用JavaScript进行单页面应用程序开发的基础知识。在进入任何客户端MVC框架之前,我想了解一些更基本的东西,比如模板插入。

我的问题:当通过_.template()呈现HTML时,不会评估模板变量。 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}));
  });
});

然而,“&lt;%= title =&gt;”在渲染输出中显示为文字字符串,应该在partial()函数中指定的实际标题不会出现。这有什么不对?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:9)

您的模板错了。您使用的是<%= ... => <%= ... %>

根据underscore documentation提供的信息,他们提供了以下示例。

var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'}); // returns "hello: moe"

支持的underscore.js模板标记为:

  • <% ... %>用于执行脚本
  • <%= ... %>插入变量(打印)
  • <%- ... %>插入变量并将其转换为HTML转发

修改

我使用了this jsFiddle。将来请提供一个例子,它让每个人都更容易。 :)

相关问题