Reputation: 455
I am trying to understand the basics of templating and have the following problem. When I try to attach ID
or/and type
attribute to the <script>
tag in my HTML code it just doesn't work:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="somescript.js"></script>
</head>
<body>
<script type="text/html" id="template1">
<form name="formXY">
<p>
<label>Field1
<input type="text" name="form_field1" value= "{{field1}}">
</label>
<button type="button">Submit</button>
</p>
</form>
</script>
</body>
</html>
I ran this in chrome/firefox/IE9/Opera and none of them parse the code between the <script>
tags. Browsers think it is just a text field. When I remove ID
and type
attributes it is again parsed correctly.
I am probably missing something very basic...
Upvotes: 0
Views: 1940
Reputation: 55402
The content of the <script>
tag is never parsed into DOM elements, the contents simply appear in the DOM as text (although <script>
is display:none;
by default so it does not appear on the page). If a type
is provided has to be one that the browser recognises before it attempts to execute it. Note that older browsers used the language
attribute instead.
Upvotes: 0
Reputation: 2879
You need to add a non javascript type
to the script tag, as the point is that you don't want the browser to parse it (as javascript), and by using a custom type
the browser will ignore it (until you grab it with javascript that is)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="somescript.js"></script>
</head>
<body>
<script type="text/x-handlebars-template" id="template1">
<form name="formXY">
<p>
<label>Field1
<input type="text" name="form_field1" value= "{{field1}}">
</label>
<button type="button">Submit</button>
</p>
</form>
</script>
</body>
</html>
And then in your javascript somescript.js
you need to get the contents of that script tag using something like this
var uncompiledTemplate = document.getElementById('template1').innerHtml;
// then pass this template to your templating engine...
// if your using handlebars:
var template = Handlebars.compile(uncompiledTemplate);
And then you can work with your template!
Upvotes: 2