Quantcast
Channel: JavaScriptMVC Forum
Viewing all articles
Browse latest Browse all 3491

Package compiled EJS templates with RequireJS

$
0
0
We're building an application with CanJS and RequireJS. I'm currently trying to package the templates into the optimized app. I have written a small RequireJS plugin which uses the official RequireJS text plugin to load the files and registers them as views:

  1. define(["lib/require-text", "can/view/ejs"], function(text) {
  2.     var buildMap = {},
  3.         escapeName = function(name){
  4.             return name.replace(/\//g, "_")
  5.         }
  6.     return {
  7.         load: function(name, req, onLoad, config) {
  8.             text.load(name+".ejs", req, function(content){
  9.                 if (config.isBuild) {
  10.                     buildMap[name] = content;
  11.                     onLoad(content)
  12.                 } else {
  13.                     require(["can/view/ejs"], function(can){
  14.                         r = new can.view.ejs(escapeName(name), content)
  15.                         onLoad(content)
  16.                     })
  17.                 }
  18.             }, config)
  19.         },
  20.         write: function(pluginName, moduleName, write){
  21.             if(moduleName in buildMap){
  22.                 var content = text.jsEscape(buildMap[moduleName]),
  23.                     name = escapeName(moduleName)
  24.                 write.asModule(pluginName + "!" + moduleName,
  25.                    "define(function () { return can.view.ejs('" + name +"', '" + content + "');});\n")
  26.             }
  27.         }
  28.     }
  29. })
It can be used like this:
  1. define([
  2.     "ejs!views/login"
  3. ], function() {
  4. var Login = can.Control( {
  5.     init: function(el, options){
  6.        el.html(can.view.render("views_login", options))
  7.     }
  8. })
This works but has the disadvantage that the templates have to be parsed every time in the client. To improve performance I want to write the template function to the optimized script rather than the original template.
I tried a "write" method like this:
  1. define(["lib/require-text", "can/view/ejs"], function(text, can) {
  2. ...  
  3.      write: function(pluginName, moduleName, write){
  4.             if(moduleName in buildMap){
  5.                 var tmpl = new can.EJS({text: buildMap[moduleName], name: moduleName})
  6.                 write.asModule(pluginName + "!" + moduleName, "define("+tmpl.fn+");\n");
  7.             }
  8.         }
  9.     }
  10. })

But the running the optimization fails with this message
ReferenceError: window is not defined
In module tree:
    insposo/insposo
      insposo/login/login
        insposo/common/ejs
          can/view/ejs
            can/util/library
              can/util/jquery
 
Is there a way to compile the template without relying on window?


Viewing all articles
Browse latest Browse all 3491

Trending Articles