How to compile jade templates in to JavaScript functions to use them on client side?

醉酒当歌 提交于 2019-11-30 18:08:37

Look for proposed solutions in the jade issue 149 discussion. Unfortunately, there is no built-in ready for use option, as I know.

Yes you can! https://github.com/techpines/asset-rack#jadeasset

I just open sourced "asset-rack", a nodejs project that can can precompile jade templates and serve them in the browser as javascript functions.

This means that rendering is blazingly fast, even faster then micro-templates because there is no compilation step in the browser.

First you set it up on the server as follows:

new JadeAsset({
    url: '/templates.js',
    dirname: __dirname + '/templates'
});

If you template directory looked like this:

templates/
  navbar.jade
  user.jade
  footer.jade

Then all your templates come into the browser under the variable "Templates":

$('body').append(Templates.navbar());
$('body').append(Templates.user({name: 'mike', occupation: 'sailor'});
$('body').append(Templates.footer());
#coffeescript
jade = require 'jade'
data = '#menu'
options = 
  client: true
  compileDebug: false
fn = jade.compile data, options
console.log fn.toString()

You should probably look at integrating this into a Grunt build task.

See grunt-contrib-jade

Blade is a Jade-like HTML template engine that has a built-in middleware for serving compiled templates to the client. :) Check it out!

This question is a bit dated, but there is a method of compiling Jade templates,

var jade = require('jade');
var fn = jade.compile(jadeTemplate);
var htmlOutput = fn({
  maintainer: {
    name: 'Forbes Lindesay',
    twitter: '@ForbesLindesay',
    blog: 'forbeslindesay.co.uk'
  }
})

Just got to the tutorial and search for compile, or the API under

 jade.compile(source, options)

Be sure to set, compileDebug so you get the source,

Set this to false to disable debugging instrumentation (recommended in production). Set it to true to include the function source in the compiled template for better error messages (sometimes useful in development).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!