Leveraging Handlebars Object within JavaScript

Is there a way to pass an entire object into javascript directly? I've tried using the {{{data}}} and {{data}} methods as suggested in other posts, but it doesn't seem to be working for me. Here's what I have in my handlebars file:

<script>
  var myData = {{data}}; // or even {{{data}}}
</script>

Both of these options result in the exception: Uncaught SyntaxError: Unexpected Identifier. However, if I try:

var myDataUrl = "{{data.url}}";

It works perfectly fine. But in the first case, it just prints out "[Object Object]". Any suggestions on how to get the first case to work correctly?

Answer №1

If you want to inject JavaScript data directly into a template, you must ensure that it is formatted as a valid JavaScript string and then pass this string into the template. It should already be in a correct format before reaching the template. Although using JSON.stringify() is a common method to achieve this, there are other ways as well.

Here is an excerpt from one of my handlebars templates where I include various JavaScript data structures within the HTML document:

<script>
// temperature data - array of arrays in the format [dateTime, atticTemp, outsideTemp]
var temperatureData = {{{temperatures}}};
// onOffData consists of [dateTime, str] pairs where 'str' can be either "on" or "off"
var onOffData = {{{onOffData}}};
</script>

The data provided to the template appears as follows (the JSON strings are returned by these two function calls):

app.get('/chart', function(req, res) {
    var tempData = {
        temperatures: data.getTemperatureDataSmallJSON(),
        onOffData: data.getFanOnOffDataSmallJSON(),
        units: req.cookies.temperatureUnits
    };
    res.render('chart', tempData);
});

As a result, a portion of the HTML file will look similar to this:

<script>
// temperature data - array of arrays in the format [dateTime, atticTemp, outsideTemp]
var temperatureData = [[1412752013861,22.19,16.35],[1412753505591,22,16.15],[1412754286561,21.85,15.94]];
// onOffData consists of [dateTime, str] pairs where 'str' can be either "on" or "off"
var onOffData = [[1411786960889,"off"],[1411790853867,"off"]];
</script>

It's important to note that the data is converted to JSON format and then passed as a JSON string to the template.

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

Dealing with currency symbols in Datatables and linking external sources

I'm having trouble linking an external link to the "customer_id" field. The link should look like this: /edit-customer.php?customer_id=$customer_id (which is a link to the original customer id). I am creating a detailed page with most of the informati ...

How can I activate JQUERY when an event occurs?

I am trying to create a selection box where, upon clicking an item on the left, it will shift automatically to the right. However, I am facing issues with using triggers to achieve this functionality. Here is the code I have written. <script type="te ...

Get started with adding a Typescript callback function to the Facebook Login Button

I am in the process of implementing Facebook login into my Angular7 application using Typescript. Although I have successfully integrated Facebook's Login Button plugin for logging in, I am facing issues with providing a callback method to the button& ...

Displaying a DIV after entering text into an <input> field using JavaScript

Attempting to create a JavaScript function that will show/hide a 'DIV' after entering some text into an input field. I have successfully written the function, but I am struggling to make it only work when the user enters a value greater than 8. ...

Display a JavaScript variable as an attribute within an HTML tag

let disableFlag = ''; if(value.action.length === 0) { disableFlag = 'disabled="disabled"'; } row += '<td><input type="checkbox" name="create" value="1" class="checkbox" data-action="'+ value.action + '" data-co ...

What is the best way to fetch information from an API using Angular5 with Material2 components?

Here are the 'table.component.html' and 'table.component.ts' files where I am pulling data from an API to display in a table. Below is the object received from the API: [ {position: 1, name: 'Hydrogen', weight: 1.0079, sym ...

Arranging an array in alphabetical order, with some special cases taken into consideration

Below is a breakdown of the array structure: [{ name: "Mobile Uploads" }, { name: "Profile Pictures" }, { name: "Reports" }, { name: "Instagram Photos" }, { name: "Facebook" }, { name: "My Account" }, { name: "Twi ...

When using Firestore in Android, I encounter a nodejs error regarding headers being sent prematurely

Currently, I am utilizing a webview in order to display content from a nodejs server. While requesting a page works as expected, accessing firestore results in an error where it seems like nodejs is attempting to resend the page. Below is the code for an a ...

What do you believe to be superior: Vue UI design?

Scenario: Application managing multiple user roles. A view with extensive conditional rendering in the template. a) Is it preferable to have numerous conditional statements in a single view's template? b) Should separate views be created for each ro ...

Display scroll bars over the position:absolute header

My container has content that exceeds its size in both directions. To see the issue, try scrolling horizontally and vertically on the table available here: The vertical scrollbar is visible as desired, except that it gets hidden behind the table header un ...

Downloading fonts from Google Fonts is always a struggle when using Next.js

After initializing a fresh Next.js project using create-next-app, I managed to successfully launch it with npm run dev. However, an issue arises every time Next.js boots up, displaying the following error: FetchError: request to https://fonts.gstatic.com/ ...

How to correctly serialize nested maps in JQuery ajax data for sending?

var locationData = { "location" : { "name" : $("#user_loc_name").val(), "street_address" : $("#user_loc_street_address").val(), "city" : $("#user_loc_city").val(), "province" : ...

Handling invalid JSON data using JavaScript

Looking to extract data from this URL using Javascript. Here is a sample of the JSON content: {"ss":[["Thu","7:00","Final",,"BAL","19","ATL","20",,,"56808",,"PRE4","2015"],["Thu","7:00","Final",,"NO","10","GB","38",,,"56809",,"PRE4","2015"]]} Most tutori ...

Leveraging the array for fetching JSON data

I'm currently utilizing this code snippet to parse json data: $.getJSON(geocodingAPI, function (json) { // Extracting variables from the results array var address = json.results[0].formatted_address; console.log('Address : ', a ...

Ways to showcase title using ng-repeat

<input type="text" ng-model= "name" title="{{name}}">//this title displays the name that is contained in ng-model Similarly... <select title ="{{item.actionId}}" ng-model="item.actionId"> <option ng-repeat="action in actionList" value="{{ ...

Leveraging web workers for asynchronous API calls

Trying to find an efficient method for utilizing web workers to handle api calls, my current approach involves the following on the client side: - worker-client.js export const workerFetch = (method = "get", url = "/", data = {}) => new Promise((res ...

Exploring the capabilities of the Express router and its various methods

I am curious about var server = http.createServer(function(req, res) { // something } server.listen(3000); Is the server created and listening on port 3000 immediately after running this code block, or is it only created at first and then started ...

JavaScript: Increasing the date by a certain number of days

I've been researching various topics and so far, I haven't come across one that addresses my specific issue. Here's the task at hand: 1) Extract a bill date in the mm/dd/yy format, which is often not today's date. 2) Add a dynamic ...

Having difficulty using JavaScript regex to replace the middle of content?

I am working with a text name[one][1][two][45][text] Through this pattern, I am able to extract the number "45" /(.*?)rows\]\[([0-9]*)(.*)/; Now, my challenge is how can I change the only 45 to a different digit? Using the same pattern and re ...

Guide to creating an ES6 express application using webpack 2 and babel

In my .babelrc file, I have only included the es2015 preset and I am using a Webpack 2 configuration for my project. I want to create an express app in ES6. Here is the webpack configuration: const path = require('path'); module.exports = { t ...