diff --git a/lib/api.js b/lib/api.js index ad4877f..bb93483 100644 --- a/lib/api.js +++ b/lib/api.js @@ -28,3 +28,87 @@ SSR.compileTemplate = function(name, content, options) { return Template[name] = eval(template); }; + +SSR.headSections = {}; + +SSR.loadTemplates = function(txt){ + // find template sections with name and inner text section in the template text + var myRegexp = /\([\s\S]*?)\<\/template\s*>/g; + var match = myRegexp.exec(txt); + + while (match != null) { + try{ + // for all the matches - compile the name(1) to text(2) using SSR + // console.log('compiling '+match[1]); + SSR.compileTemplate(match[1], match[2]); + }catch(e){ + console.log('failed to compile template '+match[1] +' error:'+e); + } + + // save this data in template + + SSR.headSections[match[1]] = match[2]; + + // get next match + match = myRegexp.exec(txt); + } +}; + +SSR.renderResponse = function (template, data, response, meta){ + // render the template itself using SSR + var res = SSR.render(template, data); + + var output = ""; + + // append a common head template - if present + if(SSR.headSections["head"]) + output += SSR.headSections["head"]; + + // if template specific head is present - append that + if(SSR.headSections[template+"-head"]) + output += SSR.headSections[template+"-head"]; + + // output += ""; + + var contentType = "text/html"; + // if meta has been defined in code - append it to the head + if(meta){ + var keys = Object.keys(meta); + for(var k in keys){ + var key = keys[k]; + var val = meta[key]; + if(key === "title") + output= output + ""+val+""; + else{ + if(val === "css") + output +=""; + else{ + if(val == "script") + output += "" + else{ + if(val == "content-type") + contentType = key; + else + output += ""; + } + } + } + } + } + + // append result + output += ""+res+""; + + //in dev mode - disable caching of responses + if(process.env.NODE_ENV === "development"){ + response.setHeader('cache-control', 'no-cache'); + response.setHeader('expires', '0'); + response.setHeader('charset', 'utf-8'); + } + + // write out the whole result + response.writeHead(200, {'Content-Type': contentType}); + response.write(output); + response.end(); +} +