What is the best way to incorporate JavaScript template code into other JavaScript code?

Just like how JS template engines such as Handlebars can be used to dynamically insert values within HTML using

<div>{{value inserted by JavaScript}}</div>
, I am interested in inserting JavaScript code within other JavaScript Code with the same {{curly brackets}} notation. For example:

 var myFunction= {{My Function}};
 var bar = myFunction(foo);

Here is an example of code defined within the My Function template:

function(foo) {
   return foo+'bar';
}

I have attempted to search on Google for a solution, but have not had much luck since most results focus on JavaScript template engines like Handlebars.

Do you have any suggestions on how I could achieve this in JavaScript within the browser?

Note: The reason behind my interest in achieving this is to create JavaScript functions that can be unit-tested in my browser and easily reused without having to modify {{template}} code in JavaScript Functions utilized by Google Tag Manager which supports {{curly brackets}} notation within its JavaScript engine.

Note 2: If implementing this directly in JavaScript proves too complex, I may resort to using a back-end language like Twig in PHP to write my JavaScript code with {{curly brackets}} and then send plain JavaScript to the browser so that my unit tests function properly and the code is reusable as is from the backend.

Answer №1

If you need to generate dynamic JavaScript code, eval() can be a helpful tool. Take a look at this illustration:

var createDynamicFunction = function(jsCode) { 
        return '(function() { return function() { ' + jsCode + ' }})()'
   },
   insertThisCode = 'alert("I am created dynamically");';

customFunction = eval(createDynamicFunction(insertThisCode));
customFunction();

http://jsfiddle.net/pLk3nsv3/1/

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

AngularJS's angular.element is currently accessing the current Document Object Model

While experimenting with angular.element, I was curious about accessing the current DOM from an ng-click event. Is there a way to do this? For example: <div ng-click="angular.element(curElement).parent()..."></div> How can I retrieve the cur ...

Another option instead of using useCallback

Forgive me if this is a novice inquiry, but I am still learning JavaScript and React. I recently discovered the necessity of utilizing useCallback to wrap callback functions in order to prevent them from being recreated constantly when used within a fun ...

What are the steps to changing the navbar's color when scrolling down?

I am having trouble changing the color of my navigation bar from transparent to black after the user scrolls down. Despite trying various methods and watching tutorials, I can't seem to get it to work. HTML <nav role='navigation' class= ...

The AudioContext feature is functioning properly on Google Chrome but experiencing issues on Safari

In Safari, I understand that audio context needs to be created after user interaction. Despite this knowledge, the code below still didn't produce the desired result. HTML <button onclick="play">Play</button> Javascript functio ...

Is it possible to enter NaN in Vue3?

Is there a way to handle NaN values and keep a field blank instead when calculating margins with a formula? https://i.stack.imgur.com/JvIRQ.png Template <form> <div class="row"> <div class="mb-3 col-sm ...

Numerous animated elements within A-frame

Is there a way to incorporate animation into an A-Frame glTF model, causing it to smoothly move 5 spaces to the left and then 5 spaces forward? Below is my current code: <a-gltf-model color="#FFFFFF" width="1" height="1" de ...

Refresh the information in a bootstrap popover following a successful ajax request

Whenever I click on a specific div, I aim to have a popover appear with a loading label as the initial content, while simultaneously sending an ajax get request to the server to retrieve data. Once the data is received, I wish to update the existing popove ...

How can I store the status of checked and unchecked checkboxes in an array of objects using Angular 7?

I have a set of checkboxes with a parent-child structure, and their values are generated dynamically in a loop. When I click the submit button, I want to capture the selected or unselected values in the specified format (as shown in the commented output) ...

Graph is not showing up when navigating through page

On my List page (List.Html), users can select multiple rows to display the data in a chart using C3. However, when clicking on the compareList() button to navigate to the Chart page (Chart.Html), the chart does not display properly. It seems that the chart ...

What could be causing the default dropdown option to vanish once another selection is made?

Check out this GIF to illustrate my query. Is there a way to ensure that when an option is selected, the default choice "Watching" appears in the dropdown menu? For the direct link to the codepen, click here. <!DOCTYPE html> <html lang="en& ...

Using jQuery to serialize parameters for AJAX requests

I could use some help figuring out how to set up parameters for a $.ajax submission. Currently, I have multiple pairs of HTML inputs (i pairs): > <input type="hidden" value="31" name="product_id"> <input > type="hidden" value="3" name="qua ...

The collaboration of TypeScript and Vue in implementing index signatures resulted in the TS7053 specification

Utilizing Vue 2.6 with vue class component along with typescript. Here is the current code snippet: private validateField(fieldType: string, e: string) { this[fieldType] = e.length > 0 } An error is being thrown: Error TS7053: Element implicitly h ...

Output JSON data from PHP for use in Javascript

Is there a way to effectively convert JSON data from PHP/Laravel into JSON for JavaScript? I have the JSON string from PHP, but it is only rendering as a string. How can I convert it to a JSON object in JavaScript? Take a look at my code below. $('#e ...

Resolve CORS error when uploading images with AJAX and Node.js using FormData

I am incorporating vanilla javascript (AJAX) to submit a form and utilizing Formdata(). The submission of the form is intercepted by nodejs and linked to a database. However, there is an issue that arises when I try to connect with nodejs after adding a f ...

Sending a message to an iframe from a different origin using JavaScript

Just starting out with JavaScript and I'm attempting to send a message to my iframe in order to scroll it. Here is the code I am using: scroll(i) { var src = $("#iframe").attr("src"); $("#iframe").contentWindow.postMe ...

Traversing a JavaScript class within a for loop

I am attempting to access the locations listed in json.responseJSON.Sites, starting with LHR on the first iteration and then NJE on the next one, and so forth. The notifications for each location are "LHR" and "NJE", respectively. Is it possible to achieve ...

Declare the variable as a number, yet unexpectedly receive a NaN in the output

I'm facing an issue with a NaN error in my TypeScript code. I've defined a variable type as number and loop through an element to retrieve various balance amounts. These values are in the form of "$..." such as $10.00 and $20.00, so I use a repla ...

Preserve the previous and current state within a React application

Within my code, there is a state called newuser that undergoes changes based on the inputs entered into the input fields. This change occurs once all input fields are filled and the submit button is clicked. The goal I have in mind is to store the current ...

Merge HTML code with JavaScript from Fiddle

There was a similar inquiry posed in this specific forum thread, however, I am encountering difficulties converting the code from JSfiddle to HTML. You can access the JSfiddle example through this link: here. I attempted to apply the suggested technique ...

Loading identical items using jQuery Ajax

I have a situation where an ajax request is returning multiple URLs which I am using to create images like: <img URL="1" /> <img URL="1" /> <img URL="2" /> <img URL="1" /> <img URL="3" /> <img URL="2" /> and so on... ...