I'd like to pass some variables into an html file I have and then send them via email. Most of that isn't very relevant to the issue so I'm going to go with a basic example.
Basic Template Literals work like so:
myLink = "google.com"
myID = "testID"
template = `Please visit ${myLink}/${myID} and let them know that ${myID} sent you.`
This would make template return:
Please visit google.com/testID and let them know that testID sent you.
I've now copied the template code into an external file and am using fs.readFileSync
to read the file into a variable. The problem is that it isn't actually evaluating the ${myLink}
and ${myID}
values after the file has been read. Is there anyway to accomplish this? If this is not possible with Template Literals can you please point me in the right direction?
Template literals (template strings) allow you to use strings or embedded expressions in the form of a string. They are enclosed in backticks `` . For example, const name = 'Jack'; console. log(`Hello ${name}!`); // Hello Jack!
Template literals are great for HTML because you can add newlines and very cleanly have dynamic classes and other attributes.
Template literals are a new feature introduced in ECMAScript 2015/ ES6. It provides an easy way to create multiline strings and perform string interpolation. Template literals are the string literals and allow embedded expressions. Before ES6, template literals were called as template strings.
I know eval is not much liked but this seems to be the only solution to your question.
eval("`"+str+"`");
You don't want to read the file, firstly that will read it as a string, and secondly there are better ways of dealing with JS modules.
What you want is to export the temple string as a function from one file and import it into the other.
File 1:
module.exports = (myLink, myID) => `Please visit ${myLink}/${myID} and let them know that ${myID} sent you.`
File 2:
const createString = require('./file1');
console.log(createString('google.com', 'testID'));
I wrote a small script that can do this without eval
let externalStringLiterals = async (string, correspondingStrings) => new Promise((finish) => {
let templateString = string
let templates = string.match(/\{.}/g)
templates.forEach((str,index) => {
templateString = templateString.replace(str,correspondingStrings[index])
index >= templates.length-1 ? finish(templateString) : ''
})
})
You can find it's documentation here too >> https://gist.github.com/netha145/abb2705cbad0e5fd7b41114aaa28bfd7
How It works? It uses regex to find {number goes here} based on a number (Kinda similar to C# string literals).
Though you need to escape user input for security reasons and to not have bugs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With