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

Is there a way to retrieve just one specific field from a Firestore query instead of fetching all fields?

I am experiencing an issue where I can successfully output all fields in the console, but I only want to display one specific field. In this case, I am trying to retrieve the ID field but I am encountering difficulties. Below are screenshots illustrating m ...

Getting rid of redundant elements in an array using Javascript or AngularJS

Case Study 1 A situation arises where an API I am using returns an array with duplicate values. var originalArray = [{id:1, value:23},{id:1, value:24},{id:1, value:22},{id:2, value:26},{id:3, value:26}]; //example Inquiry 1 -> How can I remove the du ...

Error Message: Undefined Service in Angular version 1.5.4

I'm currently developing a sample application using AngularJS 1.5.4, built on angular seed, EcmaScript 6, and with a node.js web server. For routing, I am following the guidelines provided here: https://docs.angularjs.org/guide/component-router. Howe ...

Node.js encountering unexpected pattern during RegExp match

Currently, I'm developing a script that aims to simplify local testing by creating a Node server for all my Lambda functions. My main challenge lies in extracting all the dbconfig objects from each file. To test out various patterns, I rely on . Surpr ...

Tips for navigating to a specific row within a designated page using the Angular Material table

Utilizing angular material, I have set up a table with pagination for displaying data. When a user clicks on a row, they are redirected to another page. To return to the table page, they must click on a button. The issue arises when the user needs to retu ...

Error encountered: Unexpected token '"', expecting "}". Perspective from React : It is an unfortunate occurrence which h

I'm a newbie when it comes to React and I'm currently following a tutorial. Unfortunately, I encountered an error message while the script was trying to compile: Parsing error: Unexpected token, expected "}" The issue seems to be with the &apos ...

Double submission issue with Angular form (multiple ajax requests)

My controller seems to be causing a form submission issue in AngularJS where the form is being submitted twice via a get request. Upon checking my database and the console network tab, I noticed that two submissions are logged, with the first submission sh ...

JavaScript Function for Finding the Time Difference Between Two Dates (in Years, Days, Hours, or Less than One Hour)

I need to calculate the time difference between 2 dates and display it. If the difference is greater than a year, show the number of years only. If it's more than a day, show the number of days. If it's less than a day, show the number of hours. ...

Utilizing JavaScript to manage a div's actions throughout various pages

I am currently working on an HTML project that involves having a collapsible text box on each page. However, I am struggling to figure out the best way to achieve the desired behavior. Essentially, some of the links will belong to a class that will set a v ...

Transferring an organized array to processing

My goal is to transfer an array of integers from a php file called load.php to a JS script, which will then forward it to a Processing file written in JavaScript. In load.php, I define the array and send it using JSON (the array contains a minimum of 40 i ...

Tips for storing form data in MongoDB

I'm currently working on a form and I need help extracting text from the form in order to save it into MongoDB. Here is an excerpt from my tweets.ejs file: <form method="post" action="/tweets"> <input type="text" id="txt" name="text"/> & ...

Tips for effectively recycling the describe sections in mocha test cases

My app has different modes, each with its own loading times and configurations. One particular mode has a long loading period every time a page is opened which is causing some testing challenges. Currently, I have separate test files for each section of th ...

Guide to incorporating a ZF2 module from GitHub into my application with the help of Zend Eclipse PDT

I recently set up a zf2 skeleton application using Zend Eclipse PDT and now I'm trying to integrate the "cgm/zf2-file-upload-examples" package from GitHub. However, when adding it to my composer.json file with the version "=1.0.0" and attempting to up ...

Tips for interpreting a JSON Dictionary

How can I read the JSON data and access the .mp3 file within it? I am struggling to retrieve it, anyone able to assist? This is what my code looks like: NSArray *ar = [NSArray arrayWithObject:[dict objectForKey:@"pronunciations"]]; for (NSString *key i ...

combine two 2D arrays in JavaScript

I am facing a challenge with this issue concerning 2D arrays. The task at hand is to create a JavaScript function called addArrays(al, a2) that accepts two 2D arrays of numbers, a1 and a2, and calculates their "sum" following the matrix sum concept. In oth ...

Utilizing JSON with Express version 4.11 and the bodyParser middleware

I've been trying to figure this out for hours, searching through Stackoverflow and the internet in general. I've attempted different solutions but still can't seem to get it right. As a newcomer to node.js, I managed to follow a tutorial to ...

Encountering a problem with parsing JSONObject on Android

Encountering difficulty using the Android JSON object to parse a specific response. Struggling to create code that successfully parses this response "{"r":{"f":[1,0,15,5948]}}". Attempted to utilize the code below, but encountering an error: "No value fo ...

Can you retrieve the second value using JSON.stringify?

Currently implementing JSON.stringify(data.message) which returns the following value: [ { "code":"PasswordTooShort", "description":"Passwords must be at least 6 characters." } ] I aim to extract the description value for my alert message ...

jQuery - Enlarge Tree View to the level of the selected node

I am struggling to figure out how to expand the tree view up to a selected node level. If anyone has any ideas on how to accomplish this, please let me know. For instance, if we click on 'Parent d' in the 'Category list', I want to exp ...

Using a table row as a counter in HTML

I am looking for a way to automatically assign IDs to table rows using XSLT in a systematic manner. The idea is to have the ID consist of a string followed by a counter, like this: <table> <tr id="Row1"> # it can be only a number => id=" ...