stuppid_bot

Нативный шаблонизатор Javascript (native template engine)

May 25th, 2013
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <script id="menu" type="text/html">
  2. <ul class="menu">  
  3. # for (var i = 0, l = links.length; i < l; ++i) {
  4.     <li><a href="{{ links[i].href }}"{% if (current == links[i].href) { %} class="current"{% } %}>{{ links[i].name }}</a></li>
  5. # }
  6. </ul>
  7. </script>
  8. <script>
  9.                            
  10. function template(str) {  
  11.     var temp;
  12.     return new Function('context', 'var __p="";with(context){__p+="' +
  13.         str.replace(/\{\{([\s\S]*?)\}\}|\{%([\s\S]*?)%\}|^#(.*)\r?\n?|"|\n/gm, function(m, m1, m2, m3) {      
  14.             temp = m1 ? '__p+=' + m1 + ';' : ( m2 ? m2 : ( m3 ? m3 : null ) );
  15.             return temp == null ? (m == '"' ? '\\"' : '\\n') : '";' + temp + '__p+="';        
  16.         }) +
  17.         '";}return __p');
  18. }
  19.      
  20. menu = template( val('menu') );
  21. console.log(menu);
  22.  
  23. console.log( menu({
  24.     current: '/',
  25.    
  26.     links: [
  27.         {href: '/', name: 'Главная'},
  28.         {href: '/articles', name: 'Статьи'},
  29.         {href: '/contactus', name: 'Контакты'}
  30.     ]
  31. }) );
  32.  
  33. </script>
Advertisement
Add Comment
Please, Sign In to add comment