Simple template


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

[Источник](http://sreznikov.blogspot.com/2010/01/supplant.html)


Copy this code and paste it in your HTML
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <!-- http://sreznikov.blogspot.com/2010/01/supplant.html -->
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. </head>
  7. <body>
  8.  
  9. <div id="root">
  10. </div>
  11. <script type="text/javascript" charset="utf-8">
  12.  
  13. /**
  14. * supplant() does variable substitution on the string. It scans
  15. * through the string looking for expressions enclosed in {} braces.
  16. * If an expression is found, use it as a key on the object,
  17. * and if the key has a string value or number value, it is
  18. * substituted for the bracket expression and it repeats.
  19. */
  20. String.prototype.supplant = function(o) {
  21. return this.replace(/{([^{}]*)}/g,
  22. function(a, b) {
  23. var r = o[b];
  24. return typeof r === 'string' || typeof r === 'number' ? r : a;
  25. }
  26. );
  27. };
  28.  
  29. var template = '<div class="preview"><p class="image"><a href="{url}"><img src="{thumb_src}" width="{thumb_width}" height="{thumb_height}"/></a></p><p class="caption">{caption}</p></div>';
  30.  
  31. var data = {
  32. url: 'imgs/',
  33. thumb_src: 'imgs/bus.png',
  34. thumb_width: 60,
  35. thumb_height: 30,
  36. caption: 'Трам-парам!'
  37. };
  38.  
  39. var result = template.supplant(data);
  40.  
  41. document.getElementById('root').innerHTML = result;
  42. </script>
  43.  
  44. </body>
  45. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.