Navigating through elements within underscore.js templates

Can someone please help me out? I'm finding this task more difficult than it should be, so I must be overlooking something simple...

I am working with a variable that is acting as an underscore template. Here is an example of the code snippet:

var template = '<% _.each(favorites, function(value, key) { %> <li><%= key %>: <%= value %></li> <% }); %>';

So what exactly is in 'favorites'? It is data coming from a JSON object that resembles something like this (excluding other JSON data).

"favorites" : [
    { "food" : "shrimp" },
    { "drink" : "none" }
]

I just can't seem to understand why I can't get the key/value pairs to display properly in the template. All I want is for the output to look like this:

<li>food: shrimp</li>
<li>drink: none</li>

Where have I gone wrong?

Answer №1

One good approach is to utilize a different data structure, such as a well-structured collection:

preferences: [
  {category: "color", selection: "blue"},
  {category: "animal", selection: "dog"}
];

Next, you can design your template in the following manner:

var template = [
  '<% _.each(preferences, function(choice) { %>',
    '<li><%= choice.category %>: <%= choice.selection %></li>',
  '<% }); %>'
].join('');

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

If you try to wrap an object with an anonymous function, you'll receive an error message

Consider the following straightforward example. (function() { var message = { display: function() { alert('hello'); } }; })(); When trying to implement message.display(); An error is triggered stating ReferenceError: message ...

Angular - The connections between deeply nested object models are established

I have an Angular application that is used to display company and contact person information in a text box format. Here is the code for displaying the Company Email address: <label> Company Email address</label> <input type="text& ...

Issue: $controller:ctrlreg The controller named 'HeaderCntrl' has not been properly registered

I am encountering an error while working on my AngularJS program. I have defined the controller in a separate file but it keeps saying that the controller is not registered. Can someone please help me understand why this issue is happening? <html n ...

PHP Header Redirect Not Redirecting Correctly

As a newcomer to PHP, I conducted some research and attempted to implement a solution found on Stack Overflow, but unfortunately, it did not work for me. My goal is to redirect users to another page after a specific code has been executed. Despite removing ...

The Vue template is not able to recognize the Pug language syntax within the .vue file

According to the Vue documentation: Template processing differs from other webpack loaders, as pug-loader and similar template loaders return a function instead of compiled HTML. Instead of using pug-loader, opting for original pug is recommended. Test ...

Master the art of animating ng-view transitions with AngularJS

I have 2 distinct HTML pages, namely welcome.html and login.html. These two pages are incorporated or "inserted" into a common page called index.html through the utilization of an exclusive attribute known as ngview, together with a router provider. This i ...

Storing the timestamp of when a page is accessed in the database

I am currently working on a PHP website where users can register and access exclusive Powerpoint presentations. The owner has requested that I track the amount of time users spend viewing each presentation, but I am unsure of how to display and record th ...

if the checkbox is selected, navigate to the displayed section

In my scenario, I have a total of 5 checkboxes and corresponding to each checkbox, there are 5 div elements. The functionality that I need is that when a checkbox is checked, the associated div should be displayed; otherwise, it should be hidden. The check ...

Interested in creating a Twitter bot that can automatically share images from a designated folder in sequential order. Leveraging the power of node.js

Recently, I've been following an online guide to create a Twitter bot that tweets images from a folder on my computer. While I have a vast collection of photos I'd like to share, the guide only demonstrates how to post them in a random sequence. ...

Improving code efficiency for checkboxes in upcoming TypeScript versions

Is it possible to create a single checkbox component and dynamically pass different values to it without repeating code? I have set up these checkboxes to help me check the maximum and minimum values of some API data. const[checkValMax, setCheckValMax]= u ...

Can dynamic CSS imports be unloaded in a React application?

I am facing an issue with loading two files using react.lazy and suspense: import React, { Suspense, lazy } from "react"; import { Route, Redirect } from 'react-router-dom'; const MainLayout = lazy(() => import('Components/Layout/MainL ...

Why are static PropTypes used in ReactJS and do they offer any solutions or are they merely a recurring design choice?

While delving into the code base of a web application, I came across some static PropTypes that left me questioning their purpose and necessity. Here is a snippet of the code in question: static propTypes = { fetchCricketFantasyPlayers: PropTypes.fun ...

Error occurs when attempting to execute JSON.parse within the backend of a Wordpress

My goal is to have a dropdown list of WordPress pages with the class of 'page_id' that can be repeated and added dynamically. Whenever a page is selected from the dropdown list, I want to send an AJAX request to fetch the title, excerpt, and thum ...

Understanding the timing of records being returned via an Observable in Angular's ngOnInit

In my Angular 2 application, I am using an observable to keep track of an array of records. As the results of this observable are stored in the variable "records", I am utilizing *ngFor="let record of records" to iterate over and display them in my view. ...

I am attempting to link my Firebase real-time database with Cloud Firestore, but I am encountering import errors in the process

I am currently working on enhancing the online functionality of my chat app by implementing a presence system using Firebase Realtime Database. Here is the code snippet that I have created for this purpose: db refers to Firestore and dbt refers to the Rea ...

How can function expressions result in a returned value?

Function expressions result in a value, unlike function declarations which do not. This distinction was clarified for me by others in a different SO thread (link provided). All functions default to returning undefined, hence the emphasis on "expression" ...

Performing a mouse hover action with Selenium WebDriver

Can someone guide me on how to perform a mouse hover action in Selenium WebDriver? The mouse hover action needs to be done on a tab where it hovers and then clicks on the tab. Is there a way to achieve this using JavaScript executor and java? ...

Retrieving the JSTree JSON data along with its associated metadata

We've implemented jstree as a tool for editing our navigation menu, and have been adding metadata to the tree nodes in this manner: var data = currentNode.data("jstree"); data.title = textBoxTitle.val(); data.linkType = textBoxLink.val(); Although I ...

JsonProperties do not accept values in the body of the request

Encountering an issue. The way my code generates the body for requests is as follows: @Data @NoArgsConstructor @Builder @AllArgsConstructor @ToString public class CreateCountryCode { @JsonProperty(value = "first_value") private String firstValue; ...

CSS changes triggered by JQuery are ineffective

Having trouble modifying the CSS of a class in my HTML file. I've been struggling with this for quite some time and can't figure out what I'm doing wrong. (I've already attempted multiple versions, but nothing seems to work) Here' ...