There are two separate html pages named home
and about
. Each page contains a js variable defined at the top of the page:
var pageAlias = 'home'; // on the home page
var pageAlias = 'about'; // on the about page
The goal is to pass this variable to mustache and display the values associated with that mustache key. The json file holds a list of all page headings, and the aim is to retrieve the page heading that matches the dynamic pageAlias. However, it is not functioning as intended. Below is the current code:
pageHeading.js (included in each html page):
// Page Heading
$.getJSON('page_heading.json', {}, function(templateData, textStatus, jqXHr) {
var templateHolder = $('#page_heading_template_holder');
// Defined as a var on every page, at the very top,
// so we can extract the page title from Alias using 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));
});
});
This setup allows for rendering both page_heading.json
and page_heading.mustache.html
. The latter being an external mustache file reused by both pages. The json data is plugged into the mustache template, and the
var pageHeadingData = { "pageAlias" : pageAlias}
is added and merged with the original loaded json.
page_heading.json (showing the dynamically merged pageAlias)
{
"pageHeading": {
"home": {
"title" : "Welcome to our website!"
},
"about": {
"title" : "Where we came from."
}
},
"pageAlias" : "home" // Merged dynamically from .js to acquire pageAlias
}
The problem arises when mustache fails to utilize the dynamic value of pageAlias ('home') to locate it under pageHeading and display the corresponding title:
page_heading.mustache.html (working as expected)
// This section functions properly and retrieves the title, although it lacks dynamism
<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 (not working - seeking assistance)
// In this case, the literal interpretation of pageAlias is causing issues as mustache searches for it
// within the json instead of its value, meaning 'home', thus failing to fetch the title
<script id="page_heading_template" type="text/html">
<div class="page-heading">
{{#pageHeading.pageAlias}}
<h1>{{{title}}}</h1>
{{/pageHeading.pageAlias}}
</div>
</script>
How can I achieve this and obtain the dynamic value of pageAlias to display the relevant pageHeading?