Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function extend(dst, src) {
- for (var p in src) {
- if( src.hasOwnProperty(p) ) {
- dst[p] = src[p];
- }
- }
- return dst;
- }
- function clone(o) {
- // return JSON.parse( JSON.stringify(o) );
- return extend( {}, o );
- }
- // template('Hello, ${name}!', {name: 'world'});
- // "Hello, world!"
- function template(str, context) {
- return str.replace( /(?:\$\{(\w+)\}|\{>\s*(\w+)\}|\{@(\w+)\}(.*)\{\/\3\})\r?\n?/g, function(p0, p1, p2, p3, p4) {
- if (p1 && context[p1]) {
- return context[p1];
- }
- else if (p2 && context[p2]) {
- return template(context[p2], context);
- }
- else if (p3 && context[p3]) {
- var data = context[p3];
- switch (data.constructor) {
- case Object:
- return template( p4, extend( clone(context), data ) );
- case Array:
- var temp = '', scope = clone(context);
- for (var i = 0, l = data.length; i < l; ++i) {
- temp += template( p4, extend(scope, data[i]) );
- }
- return temp;
- }
- return data;
- }
- return '';
- } );
- }
- // ${var}
- // {@segment}{/segment}
- // {> eval}
- content = template('{> header}<nav>{@links}<a href="${url}">${title}</a>{/links}</nav><h1>${title}</h1>${content}{> footer}', {
- header: '<!DOCTYPE html><head><title>${title}</title></head><body>',
- title: 'Test',
- links: [{title: 'Главная', url: '/'}, {title: 'Статьи', url: '/articles'}, {title: 'Контакты', url: '/contactus'}],
- content: '<p>It\'s works!</p>',
- footer: '</body></html>'
- });
- document.write( htmlencode(content) );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement