Solving template strings in a future context

I have a unique use-case scenario where I am filling the innerHTML like this. However, my issue lies in resolving the template literal within the context of a for loop. Any suggestions on how to accomplish this?

var blog_entries_dom = 'blog_entries';
var blog_entries = [
    {
        "title": "Hello World",
        "id": 2,
        "body": "<p>Hello World</p>"
    },
    {
        "title": "World Hello",
        "id": 3,
        "body": "<p>World Hello</p>"
    }
];

var blog_entry_template = `<div class="post-preview">
                        <a href="post.html">
                            <h2 class="post-title">
                                ${item.title}
                            </h2>
                            <h3 class="post-subtitle">
                                ${item.body}
                            </h3>
                        </a>
                        <p class="post-meta">Posted by <a href="#">Start Bootstrap</a> #Created At </p>
                    </div>
                    <hr>`;


var populate_children = function (element_id, objects_list, template) {

    var element = document.getElementById(element_id);

    var html = '';

    for (var i = 0; i < list.length; i++) {
        var item = list[i]
        html += template;
    }

    element.innerHTML = html;
};

populate_children(blog_entries_dom, blog_entries, blog_entry_template);

https://i.sstatic.net/UJILR.png

Answer №1

Template literals work as literals in JavaScript, meaning they are evaluated where they are located and cannot be passed around like objects.

An alternative approach is to encapsulate the template literal within a function that can be passed as an argument. This function should accept any necessary parameters for the template and return the evaluated result.

In this scenario, you can convert your `blog_entry_template` into an arrow function and invoke it accordingly:

var blog_entries_dom = 'blog_entries';
var blog_entries = [
    {
        "title": "Hello World",
        "id": 2,
        "body": "<p>Hello World</p>"
    },
    {
        "title": "World Hello",
        "id": 3,
        "body": "<p>World Hello</p>"
    }
];

var blog_entry_template = item => `<div class="post-preview">
    <a href="post.html">
        <h2 class="post-title">
            ${item.title}
        </h2>
        <h3 class="post-subtitle">
            ${item.body}
        </h3>
    </a>
    <p class="post-meta">Posted by <a href="#">Start Bootstrap</a> #Created At </p>
</div>
<hr>`;

var populate_children = function (element_id, objects_list, template) {

    var element = document.getElementById(element_id);

    var html = '';

    for (var i = 0; i < list.length; i++) {
        html += template(list[i]);
    }

    element.innerHTML = html;
};

To use the function:

populate_children("some-id", blog_entries, blog_entry_template);

Answer №2

Perhaps another approach could be beneficial, utilizing the prototype functionality can offer a viable solution!

String.prototype.replaceTemp = function(replaceObj) {
   return this.replace(/{\$(\w{1,20})}/g, function(matchStr, agr) {
     if (replaceObj[agr] instanceof Object || replaceObj[agr] instanceof Function) {
       var _tempPool = (window.TEMP_POOL = window.TEMP_POOL || []);
       var _length = _tempPool.length;
       _tempPool[_length] = replaceObj[agr];

       if (replaceObj[agr] instanceof Function)
         return "TEMP_POOL[" + _length + "](this);"
       else
         return "TEMP_POOL[" + _length + "]";

     } else {
       return replaceObj[agr] || "";
     }

   });
 };


    var blog_entries_dom = 'blog_entries';
    var blog_entries = [
        {
            "title": "Hello World",
            "id": 2,
            "body": "<p>Hello World</p>"
        },
        {
            "title": "World Hello",
            "id": 3,
            "body": "<p>World Hello</p>"
        }
    ];

    var blog_entry_template = `<div class="post-preview">
                            <a href="post.html">
                                <h2 class="post-title">
                                    {$title}
                                </h2>
                                <h3 class="post-subtitle">
                                    {$body}
                                </h3>
                            </a>
                            <p class="post-meta">Posted by <a href="#">Start Bootstrap</a> #Created At </p>
                        </div>
                        <hr>`;


    var populate_children = function (element_id, objects_list, template) {

        var element = document.getElementById(element_id);

        var html = '';

        for (var i = 0; i < list.length; i++) {
            html += template.replaceTemp(list[i]);
        }

        element.innerHTML = html;
    };

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 http url on an iPad in the src attribute of an HTML 5 video tag is malfunctioning

Having trouble loading a video on iPad using an http URL in the src attribute of an HTML5 video tag. Both static and dynamic approaches have been attempted, but it works fine on web browsers. Here is an example of the code: Static: <!DOCTYPE html ...

Execute the ajax function using Facebook API

I am currently working on a code to fetch data from Facebook to my localhost, but I have encountered some challenges along the way. Here are the issues that I am facing and I would appreciate any assistance: (1) Initially, I am retrieving data from a spec ...

npm causing problems with babel-cli

While working on building a section of my library with Babel, I've encountered some issues when running Babel commands through npm. In my npm script named "build," the following commands are executed: { "prebuild": "rm -rf && mkdir dist", ...

`Zooming and scrolling feature within a masked image`

I'm struggling to achieve a scrolling zoom effect similar to the website mentioned below, but I can't seem to get it to fully zoom. Additionally, when I try to zoom in on a clipped shape or text while scrolling, the entire div ends up scrolling ...

VueJS File Upload Field Failing to Reset Post Successful Submission

I am facing an issue in my VueJS application where the form does not clear all field values after submission, especially the file upload field. After a successful submission, the uploaded file name still remains displayed on the screen. Below is the code ...

Tips for avoiding the exposure of full user models in the jade template

As I work on the login functionality of my project, I'm utilizing express, passport-local, and mongoose. My code includes a series of routes: module.exports = function (app) { app.get('/', function (req, res) { res.render(' ...

Leveraging PrimeFaces and the p:ajax component, trigger Ajax within an inputText field only when keystrokes lead to changes in the field

I am currently utilizing PrimeFaces and have a p:inputText field that requires updating certain components on the view based on the most recent keystroke within that p:inputText. Below is the code snippet: <p:inputText value="#{customerLController.surn ...

Making an HTTP request within a forEach function in Angular2

Encountering an issue while using the forEach function with HTTP requests. The _watchlistElements variable contains the following data: [{"xid":"DP_049908","name":"t10"},{"xid":"DP_928829","name":"t13"},{"xid":"DP_588690","name":"t14"},{"xid":"DP_891890" ...

The error message for ExpressJS states: "Headers cannot be set after they have already been sent."

Currently, I'm facing a challenge with ExpressJS and am having trouble finding the necessary documentation to resolve it. Technology Stack: body-parser: 1.17.0 express 4.15.0 multer: 1.3.0 MongoDB Postman The current view consists of 3 fields: n ...

What is the best way to incorporate an environmental variable in my AngularJS controller?

My API Key is securely stored in my '.env' file to keep it hidden from Git. Here's a snippet of my .env file: API_TOKEN=secrettokengibberish When working on my Angular controller, I need to retrieve this variable for my AJAX call. This i ...

Implementing a sibling combinator technique within Material UI's useStyles framework

Is there a way to change the background of one div when hovering over another using material ui? The traditional CSS method is: #a:hover ~ #b { background: #ccc; } Here is my attempt with Material UI: const useStyles = makeStyles(theme => ({ ...

Navigate to a specific div with its id in ReactJS without relying on external libraries

Is it possible to scroll to a specific div using an ID in React without relying on external libraries? I've come across some solutions that involve scroll libraries. Below is the code for the div within my WrappedQuestionFormFinal component: <div ...

Mastering the Art of Managing AJAX Requests with EXTJS

I have a code to send an AJAX request that appears to be functioning correctly under firebug, sending the correct parameters: Ext.Ajax.request({ url: 'test', params:{name: "bunya"}, success: function(resp){ ...

Troubles with the compatibility of javascript and jquery's multiselect plugin

I've been utilizing the multiselect API to create a dropdown with multiple select options. This is my HTML code: <select id="options" multiple="multiple"></select> And this is my JS code: render:function(){ // $('#viewTemp& ...

execute a setTimeout function in ReactJs to render a component after a specified amount of time

Is there a way to render a component inside my App.Js after a certain amount of time using setTimeout? I've tried, but nothing seems to be happening... This is my code: function App() { return ( <Router> <GlobalStyle /> ...

What is the process for forming a series of arrays from one singular array?

If I have a large array consisting of numbers from 1 to 18, is there a simple method to split it into pairs like [1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13,14] for n=2? The special case of n=2 is all I need. ...

Using regular expressions to identify the presence of "&", parentheses, and consecutive letters in a string

I specialize in working with JavaScript and I have a need to verify if my text contains certain characters. Specifically, I want to check for the presence of parentheses (), ampersands (&), and repeating letters within the text. Here are some examples: te ...

$http({method}) is malfunctioning while $http.get is functioning properly

Issue Description: While working on my project, I encountered an issue where using $http({ method : 'GET', url : data : ..... param works fine for both GET and POST requests. However, when the same method is used in JSFiddle, it blocks my reques ...

What is the best way to clear radio button selections in a form using reactjs?

I designed a survey form with 4 radio buttons for a single question. I also included buttons to submit the form and clear input fields. However, when I click on "Clear Input," the checked radio buttons do not get cleared. How can I achieve this using the r ...

interactive form fields updating using javascript

Hey there! I'm a beginner in web development and currently facing a challenge. I have a form with 2 fields generated by one drop-down menu. I've managed to generate one field, but struggling to get the other due to my limited knowledge. I just ne ...