如何将jade模板编译成JavaScript函数以在客户端使用它们?

时间:2012-03-01 19:20:30

标签: node.js pug

我想在客户端使用已编译的jade模板。我应该如何编译它们来获取javascript文件? https://github.com/visionmedia/jade

6 个答案:

答案 0 :(得分:13)

是的,你可以! https://github.com/techpines/asset-rack#jadeasset

我刚开源“asset-rack”,这是一个nodejs项目,可以预编译jade模板并在浏览器中以javascript函数的形式提供它们。

这意味着渲染速度非常快,甚至比微模板更快,因为浏览器中没有编译步骤。

首先,您按如下方式在服务器上进行设置:

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

如果您的模板目录如下所示:

templates/
  navbar.jade
  user.jade
  footer.jade

然后所有模板都会在变量“模板”下进入浏览器:

$('body').append(Templates.navbar());
$('body').append(Templates.user({name: 'mike', occupation: 'sailor'});
$('body').append(Templates.footer());

答案 1 :(得分:4)

#coffeescript
jade = require 'jade'
data = '#menu'
options = 
  client: true
  compileDebug: false
fn = jade.compile data, options
console.log fn.toString()

答案 2 :(得分:3)

jade issue 149 discussion中查找建议的解决方案。不幸的是,正如我所知,没有内置的随时可用选项。

答案 3 :(得分:3)

您应该考虑将其集成到Grunt构建任务中。

请参阅grunt-contrib-jade

答案 4 :(得分:2)

Blade是一个类似Jade的HTML模板引擎,它有一个内置的中间件,用于向客户端提供已编译的模板。 :)看看吧!

答案 5 :(得分:2)

这个问题有点陈旧,但有一种编译Jade模板的方法,

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

刚到the tutorial并搜索编译

下的the API
 jade.compile(source, options)

请务必设置 compileDebug 以获取源代码

  

将此项设置为false可禁用调试工具(在生产中推荐)。将其设置为true以在编译模板中包含函数源以获得更好的错误消息(有时在开发中很有用)。