Creating dynamic layouts using Handlebars.js recursion

I'm working with a basic object hierarchy that includes:

Category
 String name
 List childCategories;

My goal is to use handlebars to represent this structure in a generic manner, but I'm struggling on how to nest layouts. Here's the current layout:

<script id="categories-template" type="text/x-handlebars-template">
    {{#categories}}
        <ul>
            <li>                    
                <span>{{name}}</span>       
                <div>{{#childCategories}}{{/childCategories}}</div>
            </li>       
        </ul>
    {{/categories}}
</script>

What would be the most efficient way to reuse the existing categories template for all child categories? Do I need to register a handler, or is there a simpler solution?

Answer №1

Using two different templates

<!-- showing HTML language -->

<script id="categories-template" type="text/x-handlebars-template">
{{#categories}}
    <ul>
       <li>                    
          <span>{{name}}</span>       
          {{#if childCategories}}                    
             <div>{{&testHelper childCategories}}</div>
          {{/if}}
       </li>       
    </ul>
{{/categories}}
</script>

<script id="categories-nested" type="text/html">
    {{&testHelper categories}}
</script>

Implementing a Handlebars Helper

Handlebars.registerHelper('testHelper', function(info) {
    var template = Handlebars.compile($('script#categories-template').html());
    return template(categories);
});

Answer №2

<script id="categories-template" type="text/x-handlebars-template">
    <ul>
    {{#each sections}}
        <li>                    
            <span>{{title}}</span>       
            <div>
                <ul>
                    {{#each subsections}}
                        <li><!-- content: lorem-ipsum-dolor --></li>
                    {{/each}}
                </ul>
            </div>
        </li>
    {{/each}}
    </ul>
</script>

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

The lifecycle of XMLHTTPRequest objects in JavaScript - from creation to destruction

After years of working with traditional compiled object-oriented languages like C++ and .NET programming, I decided to dip my toes into JavaScript for a new project. As I was experimenting with AJAX, I stumbled upon a perplexing aspect related to how objec ...

What is the best way to conceal all input elements in a form?

I have been attempting to conceal input elements within my form by using the code snippet below. Unfortunately, it doesn't seem to be functioning as expected... <html lang="en"> <head> <title>example</title> < ...

Learn how to deactivate the pause button with just one click and re-enable it once the popup appears using Angular2 and Typescript

Can anyone assist with solving an issue I am facing with a timer and a pause button? I need the pause button to be disabled once clicked, until a popup appears, then it should become enabled again. My code snippet is provided below: HTML: <button md-i ...

Trouble with ng-repeat when working with nested json data

Check out this app demo: http://jsfiddle.net/TR4WC/2/ I feel like I might be overlooking something. I had to loop twice to access the 2nd array. <li ng-repeat="order in orders"> <span ng-repeat="sales in order.sales> {{sales.sales ...

What are the steps involved in incorporating a REST API on the client side?

Hey there! Today I'm working with a simple Node.js express code that functions as a REST API. It works perfectly when I use Postman to send requests with the GET method, as shown in the code below. However, when I try to implement it on the client sid ...

Can someone guide me on how to locate and access the port number?

In my Reactjs project root directory, I've created a .env file. This is what's inside my .env file: PORT = 30001 ... In my App.tsx file, I'm trying to access the port like this: const PORT_NUMBER = process.env.PORT; When I run yarn start ...

Uploading files asynchronously in Internet Explorer 8

Currently, I am on the lookout for sample code that allows asynchronous file uploads in IE8 using Ajax. While having upload progress would be a bonus, it is not essential. Moreover, I specifically need PHP code to handle the uploaded files on the server ...

Trouble with React Material Modal TransitionProps triggering onEntering event

Currently, I am in the process of updating Material UI to version 5. Initially, I encountered an error stating that onEntering is deprecated and should be replaced with transitionprops. There is a specific method (let's name it doSomething) that I wa ...

Is it Possible for Angular Layout Components to Render Content Correctly even with Deeply Nested ng-container Elements?

Within my Angular application, I have designed a layout component featuring two columns using CSS. Within this setup, placeholders for the aside and main content are defined utilizing ng-content. The data for both the aside and main sections is fetched fr ...

What is the best way to transform a one-dimensional object array into a two-dimensional array in a Vue component, based on a specific key?

My vue modules are structured like this: [types.GET_PRODUCT_CATEGORIES] (state,{ stores }) { state.product_categories = {} console.log(stores); stores.forEach(message => { set(state.product_categories, message.id ...

A jQuery component with built-in event triggers

Here's an example that illustrates the concept: a widget needs to utilize its own method as a callback: $.widget("custom.mywidget", { _create: function() { this.invoke("mymodule", "myaction", {arg: this.options.value}, this.parseData); ...

After logging out, Next-auth redirects me straight back to the dashboard

In my NextJS application, I've implemented a credential-based authentication flow along with a dashboard page. To handle cases where an unauthorized user lands on the dashboard route, I've created a custom AccessDenied component. In the getServer ...

Checking the image loading functionality with Cypress

I am interested in testing Cypress to verify that an image is successfully loaded onto a page. Here is a snippet of my source code: import React from "react"; export default class Product extends React.Component { render() { return ( <div ...

Neither Output nor EventEmitter are transmitting data

I am struggling to pass data from my child component to my parent component using the Output() and EventEmitter methods. Despite the fact that the emitter function in the child component is being called, it seems like no data is actually being sent through ...

Looking to align the labels of material UI tabs to the left instead of their default center alignment? Here's how

Is there a way to align material ui tab labels to the left instead of center by default? View an image demonstrating center aligned tab labels here ...

Accessing data using the findOne or find method in Mongoose is not possible

My goal is to retrieve the amount. Here are the details: Data Schema : var schema = mongoose.Schema({ investors : { id : String, amount : Number, user_id : String, inv_profit : Number } }); Comma ...

Tips for showing/hiding textboxes based on select options:

I am currently working on a project that allows users to enter their personal information. I need help figuring out how to show or hide textboxes based on the selection made in a dropdown menu. The dropdown menu in question is for marital status. The opt ...

Generate a JSON formatted string organized by calendar year using the data retrieved from a MySQL query

For my project, I have a database table named events in MySQL. My goal is to retrieve specific data from this table in JSON format. id event 1 2010-01-01 00:00:00 2 2010-02-02 00:00:00 4 2011-01-04 00:00:00 5 2012-01-30 00:00:00 6 201 ...

Is it possible to duplicate a JSON encoded associative array?

I have a JSON string that looks like this: { "to": { "data": [ { "name": "f8", "id": "11204705797" }, { "name": "f9", "id": "11205705797" } ] } } In PHP ...

Encountering Problem with Jmeter Script Playback - Kindly Activate JavaScript to Access Page Information

I'm currently experiencing a challenge when trying to simulate the following scenario in my JMeter script. I would truly appreciate any assistance or solutions you can offer. My goal is to create a JMeter script for a form submission process within a ...