Render variable values with Mustache syntax

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?

Answer №1

The content you are attempting to retrieve is stored in pageHeading[pageAlias], a format that Mustache is unable to process. To resolve this, consider using the following method:

<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';
// Obtain the specific 'sub-object' rather than combining
// for templateData to appear like this:
// {title: 'Welcome to our website!', subttile: 'yay, you made it!'}
var templateData = pageHeading[pageAlias];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What methods can be used to disable a JavaScript function, such as utilizing hasClass()?

I am currently customizing a WordPress theme to load posts and pages using AJAX. I have successfully implemented this functionality with the code snippet below, but now I need to prevent the AJAX function from running when clicking on the logo that links t ...

Retrieve the previous value of the selection change with the Mat Select function

In my current project, I have a form with a mat-select dropdown. Whenever the user makes a selection, a dialog pops up to confirm the choice. However, I am facing an issue: The selectionChange() event is triggered when the value changes and provides the n ...

Tips for sending a JSON object from a PHP file to a JavaScript variable

Forgive me if this has already been discussed in a previous post, I have not been able to find the answer. My PHP page generates an array in JSON format: [{ "chemical":"Corrosion_Inhibitor", "TargetDose":81, "AppliedDose":26, "ppbbl":"$0.97" ...

Troubleshooting problem with Angular 2 in Internet Explorer related to the use of [style]="

I've encountered a challenge while using angular 2 (2.0.0-beta.17). The app works perfectly on most browsers, but as expected, IE 11 is causing trouble. The scripts included in the head for angular are: <script type='text/javascript' sr ...

What is the best way to create a random key using a factory function?

I am working on a function that generates objects, and I would like to be able to specify the key for the object as a parameter. However, when I try to do this, the function does not recognize the parameter properly and sets its name as the key instead. h ...

Creating a Vue.js component during the rendering process of a Laravel Blade partial view

In my Vue.js project, I have a component that is used in a partial view called question.blade.php: {{--HTML code--}} <my-component type='question'> <div class="question">[Very long text content...]</div> </my-component& ...

Using Javascript to trigger form submission using arrow keys

There are four forms displayed on a single page, and I want each form to be submitted based on the arrow key that is pressed. <form name='go_north' action='' method='post'> <input type='hidden' name=' ...

Tips on incorporating the wait function within the evaluation_now action in Nightmare?

While I am incorporating Nightmare actions in my script, a question arises regarding the use of the wait function within the evaluate_now function. How can I utilize the wait function within the evaluate_now function? I am aware that I can simply use the ...

Node.js 0.12 now offers access to the latest ECMAScript 6 features

The latest version of Node.js (0.12) has been released with an updated Google's v8 JavaScript engine, v3.28.73. Which ECMAScript 6 features are currently available in Node.js without using the --harmony flag? I have searched multiple websites that c ...

Variability in Swagger parameter declaration

Is it possible to specify input parameters in Swagger with multiple types? For example: Consider an API that addresses resources using the URL http://localhost/tasks/{taskId}. However, each task contains both an integer ID and a string UUID. I would like ...

The function '$.fn.<new_function>' is not a valid function in jQuery

UPDATE: code link with enhanced formatting: UPDATE: code upgraded with enhancements from JSHint http://pastebin.com/hkDQfZy1 I am attempting to utilize $.fn to establish a new function on jQuery objects by this method: $.fn.animateAuto = function(x,y) { ...

Angular2-starter configuration setup with environment-based variables (such as .env or .conf) for testing and production settings

Frameworks like PHP Laravel often include files for local configuration, separate from dev, test, and production environments. How can a configuration file be provided for an angular-starter project that contains all local environment variable values (su ...

How can I recreate this image in 3D using three.js?

I have a tower image' - but i don't know how to replicate this for3dview using thethree.js` any assistance would be greatly appreciated! Here is the image : This is my attempt : $(function () { "use strict"; var container, scene, cam ...

Adding a function to the Window in React & Next.js without using the onload event

Issue with External Script in React Next.js Project I am facing a problem with an external script within my React Next.js project. The script is located at . The script does not work correctly when navigating to the page using the next/link component fro ...

Struggling to properly line up the baselines of navigation list items that are styled as circular elements using CSS

I have transformed my navigation menu into a series of CSS circles with text inside. The issue I am facing is that the text spills out unevenly based on the amount of content in each circle. To address this, I used a JavaScript solution to center-align the ...

Opening a new window in JavaScript and passing additional parameters

I am facing an issue with my JavaScript link There is a hidden input field named "domain" Below is a div with an onclick script: <div id="button" onclick="window.open('http://www.mylink.nl/?domein=' + document.getElementById('domein&ap ...

Deciphering MP3 files in VB.net using JSON byte array

It's a bit of an unusual situation I've got here! I have several Android devices running custom delivery tracking software (which I developed). One of the features allows users to record a voice report and send it via mobile networks. Everything ...

Utilizing jQuery to implement a function on every individual row within a table

I have a collection of objects that requires applying a function to each item, along with logging the corresponding name and id. Below is the snippet of my code: var userJson = [ { id: 1, name: "Jon", age: 20 }, { ...

Techniques for transferring child properties and values to parent components upon the screen being initialized

Is there a way to pass property values from a child component to a parent component when the react app is first loaded? In my scenario, I have a parent component named app.js that renders a home component containing a JSON component. Initially, upon loadi ...

Click on the links to view various captions for a single image, one at a time

My goal is to create an interactive image similar to what can be found at . (Click Play and navigate to page 5 to see the interactive physical exam). While this example seems to use Flash, I am interested in achieving a similar effect using javascript/jQue ...