How to generate HTML using template literal with data coming from an object literal in JavaScript?

Issue

As the title says, I’m trying to dynamically generate my HTML buttons by using object literal data and use those to fill the template literal.

Been trying with no luck and can’t find an answer about this..

Please check the code below:

const dockButtons = {
    'list': [
        {
            'title': 'Search',
            'icon': '<i class="bi bi-search"></i>',
            'classes': 'dock-btn dock-btn-light',
            'id': 'search-links-app-icon',
            'attributes': 'type="button" accesskey="s"',
            'onclick': '',
            'access': '',
        },
        {
            'title': 'Notes & PDU Assist',
            'icon': '<img class="dock-imgs" src="../assets/links-favicons/assist.svg">',
            'classes': 'collapse dock-btn dock-btn-blue ms-2',
            'id': 'notes-and-pdu-assist-app-icon',
            'attributes': 'type="button"',
            'onclick': 'closeMainCardsList();',
            'access': '',
        },
    ]
};
const dockButtonsTemplate = `<button class="${classes} ${access}" id="${id}" onclick="${onclick}" ${attributes} title="${title}">${icon}</button>`;
const generateDockButtons = dockButtons.list.map(dockButtonsTemplate);
document.getElementById("dock-buttons-data").innerHTML = generateDockButtons.join("")
<div id="dock-buttons-data"></div>

I would also like it to be possible to create a conditional in the template, where if for example onclick object value is blank, don’t create it in the template literal.

It’s working (except the condition) if I include these lines:

const dockButtonsTemplate = ({
    title,
    icon,
    classes,
    id,
    attributes,
    onclick,
    access
}) =>

This is something I’ve learned to use recently, and so I can’t figure out how to remove the second snippet above from the tutorial I got it from. I’d like it to be directly fetching those objects if possible.

Also another question, which is faster to load, if I have say, 3000+ buttons generated from template OR 3000+ hard coded HTML buttons without using this template?

Solution

You can try this code

const btnList = dockButtons .lists;
document.getElementById('dock-buttons-data').innerHTML = `${btnList.map((btn) =>  
   <button class="${btn.classes} ${btn.access}" id="${btn.id}" 
    onclick="${btn.onclick}" ${btn.attributes} 
     title="${btn.title}">${btn.icon}</button>)}`

OR 3000+ hard coded HTML buttons is faster than 3000+ buttons generated from template

Answered By – Tamal Mallick

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.