4

I'm trying to access the html contents of an script block with the type set to "text/template". I've heard of template engines using such tags, but my application is very simple and loading an entire engine is unnecessary. Can someone shed some light on how I select that element? I think jQuery's .html() function will get me the content but I can't seem to find the element.

The template looks like:

<script type="text/template" id="repeating-form-section-template">
  <div class="repeating-form-section">
    <label>Field Name:</field>
    <input type="text" value="default value" name="field_name" />
  </div>
</script>

Things I've tried:

getElementById('repeating-form-section-template');
$('script').filter(...);
$('#repeating-form-section-template');
$("script[type='text/template']");

Thanks!

4
  • Do you need help also with template tags. This is different as you need to process them first. Commented Jun 3, 2011 at 21:52
  • I seem to have no problem with this (click here for example). You are loading the text/template part before the jQuery and then your own script, right? One other slight issue might be the malformed HTML (<label>Field Name:</field>). Commented Jun 3, 2011 at 21:54
  • This is what Im guessing if its not getting the content at all. I updated my answer too. Commented Jun 3, 2011 at 21:58
  • I forgot to trigger the function after the load event; my mistake. Thanks for the help! Commented Jun 4, 2011 at 2:13

3 Answers 3

3

Both:

 $('#repeating-form-section-template');
 $("script[type='text/template']");

Work fine. Make sure you check them after DOM load. Example: http://jsfiddle.net/niklasvh/VKqPX/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I was not loading the script after DOM load.
1

It should be this easy:

http://jsbin.com/evozi5/edit

For a preview: http://jsbin.com/evozi5/

The code tho is simply:

var someVar = $('#repeating-form-section-template').html();

$('#where-i-want-content').append(someVar);

Note

jQuery must be loaded before this will work tho. So:

<script src="jquery.js"></script>
<script> /* your code */ </script>
<script type="text/template"></script>

Comments

0

innerHTML is generally considered a bad thing to use, but it's the perfect thing to use here:

var template = document.getElementById("repeating-form-section-template").innerHTML;

document.getElementById('where-you-want-the-content').innerHTML = template;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.