Apostolos
Apostolos

Reputation: 598

Variable reference into an HTML text/html type

In JS I assign 5 to variable myVar. Then I would like to pass this variable into an HTML text/html type and show it in my demonstration div. I fail since I get 'myVar' instead of 5. Could you please someone help me.

<script>
    myVar = 5
</script>

<script id="myBlock" type="text/html">myVar</script>

<div id="DemonstrationDiv"></div>

<script>
    vBlock = document.getElementById('myBlock');
    document.getElementById('DemonstrationDiv').innerHTML = vBlock.innerHTML
</script>   

Upvotes: 0

Views: 326

Answers (2)

Taplar
Taplar

Reputation: 24965

<script>
    myVar = 5
</script>

<script id="myBlock" type="text/html">{{myVar}} is {{myVar}}, and {{myVar}} should be 5</script>

<div id="DemonstrationDiv"></div>

<script>
  var template = document.getElementById('myBlock').innerHTML;
  
  document.getElementById('DemonstrationDiv').innerHTML = template.replace(/\{\{myVar\}\}/g, myVar);
</script>

If you are not going to be doing this a lot, you can write a one off that just replaces the string with the variable value.

If you are going to be doing this a lot though, I recommend looking into Handlebars or Mustache for a complete templating library. The syntax I used here is similar to the patterns that they follow.

Upvotes: 1

symlink
symlink

Reputation: 12209

It works if you call eval() on vBlock.innerHTML

<script>
    myVar = 5
</script>

<script id="myBlock" type="text/html">myVar</script>

<div id="DemonstrationDiv"></div>

<script>
    vBlock = document.getElementById('myBlock');
    document.getElementById('DemonstrationDiv').innerHTML = eval(vBlock.innerHTML)
</script>

Upvotes: 1

Related Questions