我有两个html页面home
和about
,页面顶部定义了js变量:
var pageAlias = 'home'; // on the home page
var pageAlias = 'about'; // on the about page
我想将它传递给小胡子,并输出与该小胡子键相关联的值。基本上,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)是一个外部胡须文件,被两个页面重用。这里我们将json插入到胡子模板中,我们还添加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?
答案 0 :(得分:0)
您尝试访问的是pageHeading[pageAlias]
,而Mustache根本无法访问。你应该尝试这样的方法:
<script id="page_heading_template" type="text/html">
<div class="page-heading">
<h1>{{{title}}}</h1>
<h2>{{{subtitle}}}</h1>
<div>
</script>
{
home: {title: 'Welcome...', subtitle: 'yay, you made it!'},
about: {title: 'Where we came from', subtitle: 'and where we did not come from'}
}
var pageAlias = 'home';
// get the 'sub-object' instead of merging
// so that templateData looks like this:
// {title: 'Welcome to our website!', subttile: 'yay, you made it!'}
var templateData = pageHeading[pageAlias];