I want to do a text interpolation in HTML and JS like i usually do in angular, I know that it doesn't work if I do the exact same way:
var myPhrase = 'This is my phrase>!';
<body>
<p> {{myPhrase}} </p>
</body>
Since the angular way is "easier", I'm trying to avoid the text insertion by the myTag.innerHTML = 'something here'
So my question is: If possible how can I do it?
CodePudding user response:
Unfortunately, I don't believe you can do this in vanilla JS. Perhaps you could do something like this:
let greeting = 'Hello World!';
let message = 'How is the weather today?';
let str2 =
`<h1>${greeting}</h1>
<p>${message}</p>`;
console.log(str2);
But this does not have the same ease of use. You will probably have to use
myTag.innerHTML = 'something here'
as you said.
CodePudding user response:
It can be done but it's cumbersome and not pretty. You simpley embed script
tags in the html and document.write
output as needed.
This is one of the few examples where document.write
can be used successively as each use is occurring while the page is being interpretted.
<body>
<p> <script>document.write("hello")</script> world, <script>let phrase="how are you today?"; document.write(phrase);</script></p>
</body>
in the context of filling in stored data, each variable can be defined in an earlier script (so will be available to the future insering tags. Like this:
<script>
let myName = "David";
let myAge = "99";
let myBirthday = "tomorrow";
</script>
<h2>Hello, my name is <script>document.write(myName);</script></h2>
<p>It's my birthday <script>document.write(myBirthday);</script></p>
<p><script>document.write(`I will be ${myAge} years old`);</script></p>