Is there a way to automatically insert a variable from JavaScript inline in a text block?
I have a text block #text10, and it says something along the lines of "Once you're happy to proceed, we'll schedule your session. The session fee of $99 you pay at this point will be converted into product credit...."
I want that $99 to be a global variable so that when I change the value in the globals file, it updates throughout the site.
I have a custom JS file, globals.js where I set this:
export let globalVars = { sessionCost : 99 };
and I consume this on the relevant page(s):
import {globalVars} from 'public/globals.js'
so I can then use globalVars.sessionCost in the page's JS file. I know I can do a replace in the string, so if I replace the "99" in the text block with a placeholder of "${sessioncost}", I can do the following: $w.onReady(function () { $w('#text10').text = $w('#text10').text.replace("${sessioncost}", globalVars.sessionCost.toString()); });
This works, but it's pretty cumbersome. So I was wondering if there was an inbuilt way that I can't find to evaluate JS variables within a text block?
Thanks!
ETA: I am aware I could write this functionality myself, by iterating through all text blocks on the page, and creating my own evaluator, but if it's pre-existing functionality to insert JS variables inline, then I don't want to reinvent the wheel.
Have you found any better way to do it instead of replacing the every #text element?
You may want to use a template literal.
Why replace? Why not just build the string up with a variable?
What about something like $w("#text10").text = "Your session will be " + sessionCost.toString() + " payable up front!"