jQuery Templates: Two ways to define a template


/ Published in: jQuery
Save to your folder(s)

**Important: this snipplet has moved to Github.**

- [Method 1: Static template via a SCRIPT tag, using Jquery Templates](https://gist.github.com/1972787)

- [Method 2: Dynamic template from an arbitrary string, using Jquery Templates](https://gist.github.com/1972811)


----

Both methods work even without the *plus* extension of the [Templates plugin](http://github.com/nje/jquery-tmpl)


Copy this code and paste it in your HTML
  1. /**
  2.  * Method 1: Static template, using a SCRIPT tag.
  3.  */
  4.  
  5. //HTML:
  6. <script id="MyStaticTemplate" type="text/x-jquery-tmpl">
  7. <div>Hello ${hello}</div>
  8. </script>
  9.  
  10. //Javascript:
  11. var MyData = {hello: "world"};
  12. $("#MyStaticTemplate").tmpl(MyData).appendTo("#contents");
  13.  
  14.  
  15.  
  16. /**
  17.  * Method 2: Dynamic, from a string (which could be stored in an external
  18.  * file or even in a database]
  19.  */
  20. var MyData = {hello: "world"};
  21. $.template("MyInlineTemplate", "<div>Hello ${hello}</div>");
  22. $.tmpl("MyInlineTemplate", MyData).appendTo("#contents");
  23.  
  24.  
  25.  
  26. /**
  27.  * Note that static templates cannot be called using the dynamic method,
  28.  * therefore this would not work:
  29.  */
  30. $.tmpl("MyStaticTemplate", MyData).appendTo("#contents");

URL: http://www.wildpeaks.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.