Say I have a use case for my config file like this:
function generateText(thisIsAVariable) {
return `This is a sentence with a variable somewhere in the string
${thisIsAVariable} then more string... or not`;
}
I want to be able to import a config file that would transform the above:
import { SENTENCE_CONFIG } = "..."
// SENTENCE_CONFIG.some_sentence {"This is a sentence with a variable somewhere in the string
//[slug] then more string... or not"}
function generateText(thisIsAVariable) {
return SENTENCE_CONFIG.some_sentence;
// but have thisIsAVariable plugged in the appropriate "slug" so to speak
}
I know I can make a function to do this, but I want know if there is another way.
CodePudding user response:
One way to do this is to use a library like mustache.js
which is a logic-less template engine. It allows you to replace placeholders in a string with actual data.
// config.js
export const SENTENCE_CONFIG = {
some_sentence: "This is a sentence with a variable somewhere in the string {{slug}} then more string... or not",
};
// index.js
import { SENTENCE_CONFIG } from "./config";
import Mustache from "mustache";
function generateText(thisIsAVariable) {
const data = {slug: thisIsAVariable};
return Mustache.render(SENTENCE_CONFIG.some_sentence, data);
}
Also, the thisIsAVariable
would be better if it was an object with all the key:values
you want to replace on the config file.
For more info see: https://github.com/janl/mustache.js/
CodePudding user response:
You can create a string and add template variables inside of the string. Intentionally NOT using template ticks.
Then have a function that creates an anonymous function that returns a template literal with the string that you pass to it. Then have run call on that function to process the object passed to it.
Then simply pass a string and object of your variables.
This answer is a combination of this answer (https://stackoverflow.com/a/71801207/3684265) and a comment.
let content = {
"sentence" : "This is your sentence. ${this.thisIsAVariable} and more"
}
function vars(templateString, templateVars) {
return new Function('return `' templateString '`').call(templateVars)
}
function generateText(thisIsAVariable) {
return vars(content.sentence,{thisIsAVariable});
}
console.log(generateText("TESTT"))