Creating an extensive amount of HTML content through the use of JSON

When I request data from my API, it returns JSON objects which then populate numerous divs with content. However, I find myself continuously using concatenation to insert object properties. Is there a more efficient method for achieving this?

$.each(JSON, function(key, value) { 
  var content = display_mention(value);
  $("#mentions_container").append(content);
    });

    function display_mention(mention) {
       //this str will be much more complex and use lots of concatenation
   var str = "<div data-id='" + mention.id +"'>'" + mention.texto + "'</div></br>";
   return str;
    }

Answer №2

I find using this method for templating quite efficient:

String.prototype.template = function(obj) {
    return this.replace(/{([^{}]*)}/g,
        function(match, key) {
            var result = obj[key];
            if (!obj[key]) return "";
            return typeof result === 'string' || typeof result === 'number' ? result : match;
        }
    );
};

var info = {
  title: 'JavaScript Handbook',
  type: 'Ebook',
  category: 'programming',
  published_on: '10.15.2021'
}

var output = '<tr><td>{title}</td><td>{type}</td><td><a href="{category}">{category}</a></td><td>{published_on}</td></tr>'.template(info);

This method is straightforward and helps maintain code cleanliness.

For more robust solutions, I recommend exploring options like jQuery templates (especially if you are already using jQuery), or browsing through alternatives listed here:

Answer №3

If you don't require a larger engine, you have the option to create a straightforward template function.

function generateTemplate(str, data) {
    return str.replace(/\{([a-z]+)\}/g, function(match, key) {
        return data[key];
    });
}

To use it, simply pass an object as the context:

generateTemplate("<div class='{className}'> {content}</div><br/>", sampleData); 

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 it possible to determine if the clipboard is accessible in Firefox?

In my upcoming JavaScript project, I am looking to determine the accessibility of the clipboard. Particularly in Firefox where specific permissions need to be granted for each site in order to use certain functions like execCommand with cut, copy or past ...

When checking for errors with console.log(errors) in Ajax, it may return undefined due to server-side

I'm looking for a way to alert the user about validation errors coming from PHP. I am currently using Laravel 5.3 to build the form and Ajax to retrieve error messages. Below is my JavaScript code: $.ajax({ url: '/artistPost', typ ...

Unable to adjust metadata titles while utilizing the 'use client' function in Next.js

I have a /demo route in my Next.js 13 application, and it is using the App Router. However, I am facing an issue with changing the title of the page (currently displaying as localhost:3000/demo). The code snippet for this issue is shown below: /demo/page ...

Bootstrap: when divs cover the jumbotron

I have recently started exploring bootstrap and have been using it to build a homepage for my website. However, I am facing an issue: The three images are overlapping the jumbotron section and I can't seem to figure out why. Below is the HTML code sn ...

Tips for moving text within a Canvas using a button to trigger the function that displays the text in a Javascript environment

Within my HTML, there is a canvas element with the id="myCanvas". When a button is clicked, it triggers this particular function: function writeCanvas(){ var can = document.getElementById("myCanvas"); var ctx = can.getContext("2d"); va ...

Is there a way to halt the polling process for the specific API handling the background task?

I have been using this polling function for executing background tasks. export const poll = ({ fn = () => {}, validate = (result) => !!result, interval = 1000, maxAttempts = 15, }) => { let attempts = 1; // eslint-disable-next-line con ...

Click the link to capture the ID and store it in a variable

Currently working on a project involving HTML and JavaScript. Two HTML pages ("people.html" and "profile.html") are being used along with one JavaScript file ("people.js") that contains an object with a list of names, each assigned a unique ID: var person ...

The issue with Node.js arises when attempting to access data within a nested fs.readFile call

This is my initial attempt at a nodejs project and I'm struggling to pinpoint the issue: https://i.sstatic.net/NsI7M.png fs.readFile("/home/shaurya/Desktop/test.txt","utf-8", function(err,filedata1){ fs.readFile(filedata1,"utf-8",function(err, ...

Is it possible to retrieve text from various iframes using the rangy library?

Here's a question that follows up on a problem I've been having with grabbing selected text from iframes using rangy. The code works well for the first iframe, but when I try to grab elements from multiple iframes using the same button, it doesn& ...

What steps can be taken to integrate JavaScript into an ASP.NET control?

<script type="text/javascript"> $(document).ready(function () { $('input[name="time"]').ptTimeSelect(); }); </script> the script shown above is functioning correctly with this HTML input: <input name="time" value= ...

Select a date from the JQuery calendar, verify it against the database, and display any events scheduled for that date

I am working with a jQuery calendar that stores the selected date in a variable named "X". My goal is to retrieve events stored on that specific date from the Database and display them. Can anyone provide some guidance? <div id="calendar"></div&g ...

Eliminate the prior click action from the document object model

I am working with a set of elements that each have unique IDs and contain a span tag with the same image. For example: Under each element, there is a save icon. When a user clicks on it, the icon changes to a non-save icon. The issue arises when I click ...

What causes Gun.js to generate duplicate messages within a ReactJs environment?

I need assistance with my React application where gun.js is implemented. The issue I am facing is that messages are being duplicated on every render and update. Can someone please review my code and help me figure out what's wrong? Here is the code s ...

Why is the "module" field used in the package.json file?

Recently, I came across certain npm packages such as vue that contain a module field in their package.json files. Interestingly, the official documentation for package.json does not mention the module field - is this some kind of convention being followed ...

Sending data from a dynamically created PHP table to a modal

In my PHP-generated table, I have: <tbody> <?php $results = DB::select()->from('users')->execute(); foreach ($results as $user) { echo "<tr id='".$user['id']."'> <input type=&bs ...

Is it possible to download multiple files using a single ajax call upon success of a click function?

In my file, there are 2 anchor tags with their respective href links. I am triggering both anchor tags at ajax call success. <a id="exportExcelFatturaIcon" href ="${createLink(action: 'downloadExcel', params: [fileName:excelFileName])}" hidde ...

Trouble arising from PHP's encoded array

I am encountering an issue with retrieving a value from PHP and passing it to Javascript. The PHP array is encoded like this : echo json_encode($myArray); On the Javascript side, I use the following code within the $.ajax method: success:function (data) ...

Tips for invoking a particular function when a row in a Kendo grid is clicked

I have a Kendo grid named "mysubmissionsGrid" and I want to execute a function when each row is clicked with a single or double click. How can I accomplish this? <div class="col-xs-12 col-nopadding-left col-nopadding-right" style="padding ...

Utilize puppeteer by passing a function inside page.waitForFunction() for efficient automation processes

Below is the code I am using: function checkDataRefresh(pastAvgGain, currentAvgGain) { if (pastAvgGain !== currentAvgGain) { return true; } else { return false; } } async function fetchInformation(pair, page) { let pastAvgGain = C.AVG ...

JavaScript does not support the enumeration of programs

I'm currently working on a program that takes user input (library, authorName) and displays the titles of books written by the author. Here is an example library structure: let library = [ { author: 'Bill Gates', title: 'The Road Ah ...