Advertisement
stuppid_bot

Hogan killer

May 22nd, 2013
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function extend(dst, src) {
  2.     for (var p in src) {
  3.         if( src.hasOwnProperty(p) ) {
  4.             dst[p] = src[p];
  5.         }
  6.     }
  7.    
  8.     return dst;
  9. }
  10.  
  11. function clone(o) {
  12.     // return JSON.parse( JSON.stringify(o) );
  13.     return extend( {}, o );  
  14. }
  15.  
  16. // template('Hello, ${name}!', {name: 'world'});
  17. // "Hello, world!"
  18. function template(str, context) {    
  19.     return str.replace( /(?:\$\{(\w+)\}|\{>\s*(\w+)\}|\{@(\w+)\}(.*)\{\/\3\})\r?\n?/g, function(p0, p1, p2, p3, p4) {
  20.         if (p1 && context[p1]) {
  21.             return context[p1];
  22.         }
  23.         else if (p2 && context[p2]) {
  24.             return template(context[p2], context);
  25.         }
  26.         else if (p3 && context[p3]) {
  27.             var data = context[p3];
  28.            
  29.             switch (data.constructor) {
  30.                 case Object:
  31.                     return template( p4, extend( clone(context), data ) );
  32.                    
  33.                 case Array:
  34.                     var temp = '', scope = clone(context);
  35.  
  36.                     for (var i = 0, l = data.length; i < l; ++i) {
  37.                         temp += template( p4, extend(scope, data[i]) );
  38.                     }
  39.  
  40.                     return temp;                              
  41.             }
  42.            
  43.             return data;
  44.         }
  45.        
  46.         return '';
  47.     } );
  48. }
  49.  
  50. // ${var}
  51. // {@segment}{/segment}
  52. // {> eval}
  53. content = template('{> header}<nav>{@links}<a href="${url}">${title}</a>{/links}</nav><h1>${title}</h1>${content}{> footer}', {
  54.     header: '<!DOCTYPE html><head><title>${title}</title></head><body>',
  55.     title: 'Test',
  56.     links: [{title: 'Главная', url: '/'}, {title: 'Статьи', url: '/articles'}, {title: 'Контакты', url: '/contactus'}],
  57.     content: '<p>It\'s works!</p>',
  58.     footer: '</body></html>'
  59. });
  60.  
  61. document.write( htmlencode(content) );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement