Fill a .js script with moustache.js

I need help with organizing some JavaScript code that needs to access server-side data. I want to keep this code in a separate .js file, but I'm having issues populating it with the necessary server information using moustache. Here is my current setup:

<body>


  <script type="text/javascript" src="/js/test.js"></script>
</body>

This is what my .js file looks like:

var testField = '{{someValue}}';
alert(testField); // returns null

Any suggestions or solutions are greatly appreciated.

Answer №1

If you're looking to dynamically execute JavaScript code, one option is to utilize the eval function. However, it's important to note that eval comes with security risks and should be used cautiously. You can find more information about eval on Mozilla Developer Network.

    var dynamicCode = '{{someValue}}';
    var renderedCode = Mustache.render(dynamicCode, view);
    var result = eval(renderedCode);
    alert(result); 

Keep in mind that evaluating code using eval can expose your application to vulnerabilities, so always validate and sanitize user input.

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

What is the best way to show the current value of a checkbox element in the future?

I want to add multiple checkboxes using this method: $(".btn-sample").on("click", function() { $(".container").append( '<input class="check-sample" type="checkbox" value="'+check_value+'"/>' ); }); The issue I' ...

Tips for accessing .js variables in .ejs files

I am facing an issue with my index.js and list.ejs files in Express. Here is the relevant code: index.js: const express = require("express"); const app = express(); app.set("view engine", "ejs"); app.set("views", __dirname + "\\views"); let ...

Showcase Pictures from a Document

Is there a way to upload an image via an input field and display it? I want to showcase a profile picture that can be saved in a database. The process should be simple for the user, with the ability to easily upload and view the image. function Save() { ...

The Power of Json, Ajax, and Javascript

Is there a way to regularly check for updates and update the relevant cell accordingly? I want the updated cell to flash and change color to red/green based on if it is a negative or positive numeric value. I will be using JQuery, Ajax, and JSON... Best ...

Numerous Fascinating Challenges with React Native

Looking to share my React Native project and seeking help with some issues I'm facing. Despite multiple attempts, I have been unsuccessful in resolving them. Can anyone provide assistance? I have thoroughly searched Stack Overflow for similar questio ...

Present the value of an object within an array in an HTML format

I have organized an array containing information about different video games: let games = [{ title: 'Fortnite', price: 20, img: "./assets/images/Fortnite.jpg" }, { title: 'Valorant', price: 0, img: "./asse ...

What could be causing the issue with "class not being recognized as a constructor" error that I am encountering?

When attempting to create an instance from modules in routing, I consistently encountered the error message "class is not a constructor." Below is the code snippet: export class Modules{ modules : object = { masterdata : MasterdataModule, shop : ...

Remove any words that are not included in the specified list

Here is the code snippet to achieve the desired functionality: const { words } = require("../../json/words.json") const args = message.content.split(' ') const wordss = words.filter(m=> m.includes(args)) if(args > 1 || !wordss) { ...

Generating URL parameters for Ajax requests on the fly

My current project involves creating a dynamic form where the number of fields displayed changes based on the user's selection from a dropdown menu. This means that depending on what option they choose, anywhere from 2 to 20 different fields may be sh ...

Guide to using vite-plugin-rewrite-all in conjunction with Quasar for Vue 3 - or alternative method to enable periods in paths

Encountering a 404 error when using quasar+vite in vueRouterMode: 'history' mode with paths containing a period/dot in the id? This issue has been discussed in various places: https://github.com/vitejs/vite/issues/2415 https://github.com/vitejs/ ...

Streaming data from BigQuery to the front-end using Express

Trying to extract a query from BigQuery and stream it to the frontend has been quite a challenge. In the Node.js environment with Express, one would assume it should look something like this: app.get('/endpoint', (req, res) => { bigQuery.cr ...

Changing the Style of a CSS Module Using JavaScript

Embarking on a journey into Javascript and React, I am currently working on my first React app. My aim is to adjust the number of "gridTemplateRows" displayed on the screen using a variable that will be updated based on data. Right now, it's hardcode ...

Show information retrieved from fetch api

Hi there! I've been trying to fetch data from the Avascan API and display it on my HTML page, but so far, I haven't had any luck. I've experimented with using the Fetch API, JSON, and AJAX methods, but none of them seem to work for me. Do yo ...

Can JavaScript be used to create a CSRF token and PHP to check its validity?

For my PHP projects, I have implemented a CSRF token generation system where the token is stored in the session and then compared with the $_POST['token'] request. Now, I need to replicate this functionality for GitHub Pages. While I have found a ...

Error: The function "execute" has not been declared

Hey there! I've created a Discord bot that is meant to check the status of a Minecraft server, but I'm encountering an issue with the embed. It's showing this error: UnhandledPromiseRejectionWarning: ReferenceError: execute is not defined. ...

What is the best way to create direct links to tabs using #anchors in JavaScript?

I am managing a website that includes info-tabs based on a template I found at this link. The tabs contain anchors like example.com/#convey, but unfortunately, direct links to specific tabs using #anchor do not work properly due to the tabs relying on Java ...

Run a script on an ajax requested page prior to the page being loaded

My website navigation utilizes AJAX for seamless transitions between pages. Specifically, I have two pages: index.html and profile.html. The structure of both pages is as follows: <html> <head> <script src="script1.js" type="text/javascript ...

Issue NG0203 encountered during material import attempt

I've been encountering an issue with importing material. Despite using code similar to the examples on material.angular.io, I keep running into the ""inject() must be called from an injection context..." error. My goal is to create a simple table ...

I am experiencing an issue with my Node.js query, as it is not successfully adding a user to my database using

I'm currently working on developing an API using Node.JS, express, and MySQL with the Sequelize ORM. I wanted to do this project properly without relying on the CLI for every task. However, I've encountered a problem where my API fails to create ...

Adjust the color of the entire modal

I'm working with a react native modal and encountering an issue where the backgroundColor I apply is only showing at the top of the modal. How can I ensure that the color fills the entire modal view? Any suggestions on how to fix this problem and mak ...