Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an embeded HTML template using <script type="text/template"> using jquery

Tags:

html

jquery

I would like to create HTML templates that can be called form jQuery using script tags and then be able to show the HTML using jQuery.

<script type="text/template">
   <div id="new-post">
     <form>
       <label>Post Title</label>
       <input type="text" id="post-title"/>
       <input type="submit" value="Save"/>
     </form>
   </div>
</script>

I have found other post on stackoverflow.com, but none are what I'm looking for. Any advice on how to get this working would be appreciated.

like image 424
Carl Weis Avatar asked Aug 03 '11 20:08

Carl Weis


1 Answers

What you're trying should work OK. If you have something like this:

<script type="text/html" id="post-template">
  <div id="new-post">
    <form>
      <label>Post Title</label>
      <input type="text" id="post-title"/>
      <input type="submit" value="Save"/>
    </form>
  </div>
</script>

You should be able to do this to extract the template:

var template = $('#post-template').html();

Better yet, look into using jQuery templates. See this documentation for a good overview of how they work.

like image 130
Jacob Avatar answered Sep 26 '22 00:09

Jacob