Using Handlebars.js to dynamically set classes based on key/value pairs in JSON data

Today, I delved into the world of Handlebars.js and sought a straightforward approach. Let’s set the stage: We are unable to control how the JSON data was generated (thus, server-side solutions are out). The JSON will consist of one or more records, each containing a Message_Type name/value pair with values that hold relevance for certain functions involving CSS classes in presentation.

For example: message types may include basic, ad, notification, warning, critical, etc., with corresponding CSS classes. For instance, a critical message type might be styled with classes such as .msg_box and .critical_msg.

My question is this: How should I tackle this issue without altering the original source? Option 1: Process the JSON data before passing it to Handlebars, adding new name/value pairs for each record that specify the required classes. Option 2: Implement a solution within Handlebars itself—which remains unclear to me.

Answer №1

I think the best way to handle this with Handlebars is to parse your JSON data and dynamically assign the necessary class names before passing it to the Handlebars template. While there are ways to manipulate Handlebars to include logical operators, such as discussed in this Stack Overflow thread, it's generally not recommended.

var messageMapping = {
  basic: 'msg_box',
  ad: 'msg_box',
  notification: 'msg_box',
  warning: 'critical_msg',
  critical: 'critical_msg'
};

// Your JSON data from the server
var yourJSON = '[{"message_type":"basic", "value":"test"},{"message_type":"warning", "value":"test"}]';

var data = JSON.parse(yourJSON),
    i = 0,
    l = data.length;

// Assign the class names
for(; i < l; i++){
  data[i].msgClass = messageMapping[data[i].message_type];  
}

// Render the template
var source   = $('#template').html();
var template = Handlebars.compile(source);

$('body').append(template({messages:data})); 
.critical_msg{
  background-color:red;  
}

.msg_box{
  background-color:green;  
}
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script id='template' type='template/text'>
{{#each messages}}
  <div class="{{msgClass}}">{{value}}</div>
{{/each}}
</script>

Answer №2

Handlebars was intentionally created to operate without heavy logic, meaning it lacks built-in features for making decisions based on data other than a simple if statement regarding the existence of certain data. It does not intrinsically support determining what HTML class to apply based on the value of a data element.

Given this limitation, there are several approaches you can take:

  1. If the templates are used on the client-side, preprocess the JSON data before sending it to the template in a format that doesn't require complex logic.

  2. Create custom helper functions that can receive data and make decisions based on it, then communicate those decisions back to the template.

  3. Integrate helper methods that extend Handlebars' capabilities by adding more advanced logic features (there are existing pre-built ones available).

  4. Consider transitioning to a different template engine that offers more extensive built-in logic capabilities.

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

Issue encountered when retrieving JSON Array

Utilizing JSON for dual functionality: sending the (Username & Password) to a PHP file to retrieve toggle button status from database, as well as receiving the toggle status back in JSON format. However, when combining both functionalities to send and rece ...

Having issues with $_POST not retrieving values from .post

Below is the javascript snippet that I have written: function submitForm() { var name = document.getElementsByName('name').value ,email = document.getElementsByName('email').value ,subject = document.getElementsBy ...

Stop closing the bootstrap modal popup when the space key is pressed

Is there a way to prevent the model popup from closing when the space or enter key is pressed on the keyboard? I have already tried using data-backdrop="static" data-keyboard="false" but it still closes. Additionally, I have ensured that the form tag is no ...

How to replicate a WordPress menu bar

Embarking on my coding journey, I've completed courses in HTML, PHP, CSS, JavaScript, and MySQL. Now, I've decided to dive into hands-on learning by creating a Wordpress child theme. My current challenge is figuring out how to overlay two differ ...

Using Angular2 observables to parse JSON with a root element

I am completely new to working with Angular observables and I find myself a bit bewildered by how it all functions. Recently, I was handed an Angular CLI application that is mostly operational, but now I need to connect it to my existing API. Within my se ...

Encountering a Laravel Nova issue where attempting to override a Vue component leads to a Vue warning: Error

Recently, I decided to incorporate a user guide into my nova using the following Vue Shepherd library. To make this work, I made some adjustments in the files within the nova directory. One of these changes involved renaming the file "webpack.mix.js.dist" ...

"Is it possible to use a Twitter widget with Mootools

I have been attempting to create a marquee for my twitter Account on my website. After some trial and error, I was able to achieve this using jQuery. Here is the code I used: <div id="twitter"> <p> Loading.....</p> <n ...

Ways to invoke external jQuery functions within Angular applications

In the midst of working on an Angular CLI Project, I find myself needing to incorporate some jQuery functionalities. To accomplish this task, I have added the necessary JavaScript files in the angular.json configuration: "scripts": [ "node_modules/jq ...

Responsive design parameters

After creating a media query specifically for phones, I realized that I needed one for desktop as well. @media screen and (max-device-width: 480px), screen and (max-width: 480px) { ...css here... body {width:50%;} However, when I attempted to add a sim ...

What is the best way to send an array of objects to a Jade template?

I'm looking to retrieve an array of objects from MongoDB and pass it to the client... Here is an example object: var objeto_img= { name:'name of the file', ...

Resolved issue with maintaining scroll position after adjustments to scroll height

Currently, I am in the process of creating a chatroom that includes pagination. The issue I am encountering is related to loading old messages when the scroll height reaches 0. However, unlike platforms such as Facebook and Slack, even when the scroll he ...

Tips for exiting a function at a particular point

How can I ensure that my async function only returns at a specific point and not void at the end? const fun = () => { const list = []; let streamFinished = 0; let streamCount = files.length; await fs.readdir(JSON_DIR, async(err, files) => ...

Issues with Jquery and revslider functionality in React.js are causing problems

Just getting started with react.js and diving into the world of react development. Encountering an issue while converting static HTML to react.js where jQuery scripts only execute after manually refreshing the page, causing a slowdown in React speed. T ...

Concealing the BrowserStack key within Karma

Currently in the process of developing a JavaScript application, I am running tests using Karma on BrowserStack with the assistance of the karma-browserstack-runner. According to the guidelines, the accessKey and username should be included in the karma co ...

The ng-model is being set to the default value, however the select element fails to display the text and instead appears blank

Having trouble displaying a default option in a select tag after retrieving a list of options from the server. The model is being set correctly, but the select shows up blank, and I can't figure out why! I've attempted various solutions from Sta ...

The process of running npm build is not resulting in the creation of the bundle.js file

I've read through many Q&A threads where people are facing the same issue, but I still can't figure out what's wrong with my code. When I run 'sudo npm run build', no bundle.js file is being created.** This is my code: index ...

Utilizing Laravel's Eloquent ORM to filter columns containing JSON data

Currently, I am developing a data filter that involves filtering a column containing JSON formatted data. The table has a structure resembling the following: ____________________________________ | id | name | tags | |____|_________|_______ ...

Is there a way to enable hover functionality on mobile devices? I wish for the hover effect seen on desktop to be triggered automatically on mobile devices

I attempted to implement @media (hover: hover) without success. In my design, I have three images in a row that reveal a text overlay when hovered over with a mouse. However, the issue arises when I try to switch to a mobile view, as the images remain un ...

Is there a way to direct a message to a particular channel in Discord.js without the use of a message object?

I'm working on a bot that will post a random question from a .json file to a specific channel every two hours. Since it's not part of an event listener, I'm unable to use a message object for sending messages. I attempted to specify the cha ...

What could be causing my dropdown menu to vanish unexpectedly after being clicked for the first time?

To view the live demonstration, simply click here. I have an issue with my drop down menu where it is hidden upon first click. Additionally, I would like the drop down menu to disappear when clicked anywhere outside of its current display. How can I accomp ...