Manuel Di Iorio
Manuel Di Iorio

Reputation: 3771

*jade* precompile templates to use in the next time

I need to precompile the function to compile a jade template. After, I will can use eval() to compile this function with the local options specified.

Theorically, I have found in the source jade.compileClient (previously called as options.client) but calling this function raises an unexpected error saying "jade is not defined"

code example:

precompiled = "[" + jade.compileClient(source, {filename: myFilenameExample}) + "]";
fn = eval(precompiled)[0]; //compilation
html = fn(options); //execution

Same problem with Handlebars using handlebars.precompile() :'(

No problems, instead, with EJS using ejs.compile({client: true})

Upvotes: 0

Views: 568

Answers (2)

alex
alex

Reputation: 12275

Okay, here is how you can bundle jade with your template:

$ echo 'var jade = (function() { var exports={};' > build.js
$ cat node_modules/jade/lib/runtime.js >> build.js
$ echo 'return exports;})();' >> build.js
$ jade -c -D < template.jade >> build.js 
$ echo 'console.log(template({}))' >> build.js
$ node build.js

Upvotes: 1

Ryan
Ryan

Reputation: 5983

I may not fully understand your question. But it seems like this would do what you want:

var _jade = require('jade');
var template = process.cwd() + '/views/index.jade';

// get template from file system
fs.readFile(template, 'utf8', function(err, file){
  if(err){
    //handle errors
    console.log('ERROR!');
    return res.send('ERROR!');
  }
  else {
    //compile jade template into function
    var compiledTmpl = _jade.compile(file, {filename: template});
    // set context to be used in template
    var context = {title: 'Express'};
    // get html back as a string with the context applied;
    var html = compiledTmpl(context);
    // do something with html
  }
});

Upvotes: 0

Related Questions