【发布时间】:2014-10-29 18:30:20
【问题描述】:
我有两个html页面home和about在页面顶部定义了一个js变量:
var pageAlias = 'home'; // on the home page
var pageAlias = 'about'; // on the about page
我想将它传递给 mustache,并输出与该 mustache 键关联的值。基本上,json有一个所有页面标题的列表,我想拉取与动态pageAlias匹配的页面标题。但不为我工作。这是我所拥有的:
pageHeading.js(包含在每个 html 页面中):
// Page Heading
$.getJSON('page_heading.json', {}, function(templateData, textStatus, jqXHr) {
var templateHolder = $('#page_heading_template_holder');
// defined on every page as a var on the very top
// to pull in page title from Alias, so we can call it in mustache
var pageHeadingData = { "pageAlias" : pageAlias}
// merge pageAlias with json data
var templateData = $.extend(templateData, pageHeadingData);
$.get('page_heading.mustache.html', function(template, textStatus, jqXhr) {
templateHolder.append(Mustache.render($(template).filter('#page_heading_template').html(), templateData));
});
});
这允许我们渲染page_heading.json 和page_heading.mustache.html (mustache.html) 是一个外部的 mustache 文件,被两个页面重用。这里我们将 json 插入到 mustache 模板中,我们还添加了var pageHeadingData = { "pageAlias" : pageAlias} 并将其与原始加载的 json 合并。
page_heading.json(显示合并后的 pageAlias)
{
"pageHeading": {
"home": {
"title" : "Welcome to our website!"
},
"about": {
"title" : "Where we came from."
}
},
"pageAlias" : "home" //merged dynamically from .js to get pageAlias
}
现在的问题是小胡子无法获取 pageAlias 值,home,在 pageHeading 下找到它,并渲染出标题:
page_heading.mustache.html(工作)
// This works and pulls the title, but is not dynamic
<script id="page_heading_template" type="text/html">
<div class="page-heading">
{{#pageHeading.home}}
<h1>{{{title}}}</h1>
{{/pageHeading.home}}
</div>
</script>
page_heading.mustache.html(不工作 - 需要帮助)
// This does not work, pageAlias is taken literally and mustache looks for it
// in json not it's value, 'home', so the title is never returned
<script id="page_heading_template" type="text/html">
<div class="page-heading">
{{#pageHeading.pageAlias}}
<h1>{{{title}}}</h1>
{{/pageHeading.pageAlias}}
</div>
</script>
如何实现,获取pageAlias动态值,渲染出对应的pageHeading?
【问题讨论】:
-
为什么不直接在 JS 端设置标题,而不是在模板端进行复杂的查找呢?只需设置
{title: "whatever"}并丢弃pageAlias。
标签: javascript json mustache