我刚刚开始使用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>这里也是JavaScript of app.js:
$(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 =>“在呈现的输出中显示为文字字符串,而本应在分部()函数中赋值的实际标题则不会出现。这里怎么了?任何帮助都是非常感谢的。
发布于 2013-11-20 14:54:38
你的模板错了。您使用的是<%= ... =>,而应该是<%= ... %>。
根据来自underscore documentation的信息,它们提供了以下示例。
var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'}); // returns "hello: moe"支持的underscore.js模板标记是:
<% ... %><%= ... %>用于插值变量(打印)<%- ... %>对变量进行内插并将其转义编辑
我用的是this jsFiddle。在未来,请提供一个例子,它使一切更容易为每个人。:)
https://stackoverflow.com/questions/20098762
复制相似问题