What is the optimal method for displaying dynamic HTML content?

Imagine a scenario where I have an HTML template file with the following string:

<p> >>LEFT PART<< {{Data}} >>RIGHT PART<< </p>

Suppose that neither the left nor right part of this string contain anything like {{Data}}, and I want to create a function that takes this file and an object such as

{Data:"My nice data",Name:"Sebastian"}
, and returns a file containing:

<p> >>LEFT PART<< My nice data >>RIGHT PART<< </p>

It is achievable using string.prototype.replace, but now I have a few questions:

  1. How do JS template engines handle similar tasks? Let's focus on Jade for specificity, but feel free to discuss other engines like Pug, Dot etc. Do they rely on Regular Expressions or use complex algorithms to search for substrings?
  2. If both the left and right parts of my string contain around 10000 characters, or if the HTML file encompasses over 100 lines of code, will there be a noticeable impact on execution speed if I utilize Regular Expressions?

P.S. While I've tried to find answers via Google, most resources explain how to render a page using a framework/engine rather than delving into the internal workings.

Answer №1

In response to your two inquiries, here is what you need to know:

  1. When it comes to simpler JS templating libraries, they typically locate the opening character(s) using a basic JS String#indexO call. However, more advanced libraries, especially those that do not create their own templates from scratch, often utilize more intricate techniques.

    For instance, Vue uses lodash.template in its templating engine, which heavily relies on regexes under the hood.

  2. It is not recommended to use regex for this task because regular expressions start traversing their state machine every time they initiate a match. This can result in significant processing overhead on large strings, unlike the "indexOf" technique mentioned in point #1. It's crucial to consider this factor when working on a substantial or highly concurrent project.

One important thing to note: Many modern JS templating engines, including Vue, convert the template into smaller strings before replacing the template string. This approach allows them to take advantage of improved runtime performance and parallelization when dealing with shorter strings.

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

display upcoming schedule and time

How can I display the future date and time in the respective field components? See below for a sample code snippet: require([ "dojo/_base/lang", "dijit/registry", "dojo/ready", "dijit/form/TimeTextBox", "dojo/parser" ], function(lang, registry, ready ...

Issue with Nextjs 13: Unable to locate 'src/app/dashboard/layout.tsx' (deleted optional layout)

Deciding to start a fresh Nextjs 13.4.5 project, I set up an app directory. Within the app directory, I created a new dashboard directory and added page and layout components. Everything seemed to be functioning smoothly with two layout components - one i ...

How come the state update result is triggering two different responses?

I recently developed a basic TicTacToe game using react-hooks. At times, I notice that the result is displayed before the state update on the screen. https://i.sstatic.net/LMDeZ.png Other times, the result shows up after the update is visible on the scr ...

Can images and models be imported into three.js from a byte array?

Is it feasible to load images and models directly from byte arrays in three.js? For instance, downloading a compressed file, extracting it in JavaScript, and feeding the byte array into the loaders? Thank you ...

How can I extract an object from an array by using a string key in either Observable or lodash?

How can I retrieve a specific object (show) from Shows based on its id being a string in a given sample? I am transforming the result into an RXJS Observable, so using functionalities from RXJS or lodash would be greatly appreciated. //JSON RETURNED with ...

Using Javascript/JQuery to extract numbers from a URL with regex or alternative methods

I need help extracting a specific group of consecutive numbers from the following URLs: www.letters.com/letters/numbers/letters" and www.letters.com/letters/letters/numbers/symbols Is there a way to isolate only the continuous sequence of numbers in th ...

How come setting setTimeout to zero did not cause the code to enter an endless recursive loop?

I found this snippet of code on a website that discusses async callback functions and the event loop in JavaScript. I am curious as to why the line timer = setTimeout(arguments.callee, 0) does not create a recursive loop since it is being executed withou ...

PHP function json_encode() is causing an issue by returning an "Undefined" value

I'm working on a PHP project where I am creating an array and using json_encode() to convert it into JSON before retrieving it with $.getJSON. However, I am encountering an issue where it returns Undefined when trying to send all the data at once. Int ...

Regex isn't functioning as expected

During my coding process, I encountered an issue with extracting a specific string from the Source Code: Plange Mühle 1, 40221 Düsseldorf. My goal was to filter out everything before the comma, then extract the number, followed by the remaining word. Ini ...

I am experiencing difficulty with Three.js rendering textures from my planet constructor function

I am facing an issue with my function that is supposed to create a 3D object (a planet) using orbital parameters and texture images from a dataset. Strangely, the textures are not rendering when I use StandardMaterial or PhongMaterial, even though they wor ...

What is the method to apply a class exclusively to an img tag?

While using the Cycle2 Carousel plugin, I encountered an issue with the class being set for my thumbnails. The plugin sets the .cycle-pager-active class for both images and divs, which is not ideal. I attempted to fix this by adding 'img' before ...

Creating a date in the style of a credit or debit card expiration date

I need to create dates in the format of 'Thru: 12/20' (similar to a credit/debit card expiration date). How can I generate a date in this specific format? new Date().toJSON().slice(0,7).split('-').reverse().join('/') Although ...

Is there a way to change the text (price) when I select an option?

<div class="single-pro-details"> <!--Customize in the CSS--> <h6>Home / Beats</h6> <h4>Unique Lil Tecca Type Beat - New Love</h4> <h2 id="price">$ ...

Creating secure hashes in NodeJS/JS for JSON objects and strings through sha256 concatenation

Hello there, I'm looking to hash object parameters and a string (concatenation) using sha256, but I am unsure of the correct method. Here is my object: const params = { "name": "kacper", "age": 23 }; const text = "string to hash"; I at ...

Unable to save the ID of an element into a jQuery variable

I am currently working on a project that involves an unordered list with anchor tags within it. I am trying to access the id of the li element that is being hovered over, but for some reason, the alert is returning undefined or nothing at all. Here is the ...

Oops, it seems like the project is missing a `pages` directory. Please kindly create one in the project root. Thank you!

Initially, my project setup looked like this: public .next src pages components assets next.config.js It was functioning properly, but I made a structural change to the following: public src client next.config.js jsconfig.json pa ...

The div is unable to display data retrieved from the php file using Ajax

This is the function utilizing ajax $(document).ready(function() { $('#submit').click(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: 'searchphp.php&apo ...

Guide to deactivating the selected value in a dropdown list (vue.js 2)

Here is an example of my component structure : <div id="demo"> <div> <select class="form-control" v-model="selected" required> <option v-for="option in options" v-bind:value="option.id">{{ option.name }}</option> ...

Modify and improve promise and promise.all using the async/await feature of ES2017

I have successfully implemented a photo upload handler, but I am now exploring how to integrate async await into my code. Below is the working version of my code using promises: onChangePhotos = (e) => { e.preventDefault() let files = e.target ...

Crafting a variety of elements using Power BI's custom visual feature

I'm struggling with creating multiple objects based on input data. I've tried using an array, but it requires knowing the number of objects in advance. Does anyone have a solution for this? Here is my code snippet - module powerbi.extensibilit ...