服务客户端Jade模板

我想用Backbone在客户端使用Jade模板。 我怎样才能做到这一点?

现在,我已经成功configuration了Backbone(Marionette)来编译Jade模板,以便在其视图中使用:

Marionette.TemplateCache.prototype.compileTemplate = (tmplStr) -> console.log "jade stuff: ", jade.compile(tmplStr) return jade.compile(tmplStr) 

“问题”是:我目前正在写模板,如:

 script(type="text/template", id="tmplMainView") | h1= title | p= content 

注意这些pipe道( | ),以防止Jade试图在服务器端解释/parsing它们。 我怎样才能消除这些?

UPDATE

也许我可以使用jade --client标志…但它提供了一个单一的编译function:例如

 h1= title 

 function anonymous(locals, attrs, escape, rethrow, merge) { attrs = attrs || jade.attrs; escape = escape || jade.escape; rethrow = rethrow || jade.rethrow; merge = merge || jade.merge; var buf = []; with (locals || {}) { var interp; buf.push('<h1>'); var __val__ = title buf.push(escape(null == __val__ ? "" : __val__)); buf.push('</h1>'); } return buf.join(""); } 

这意味着我必须有一个Jade /编译每个模板的JS? 我该如何使用它? 另外我觉得很多JS文件是一个慢的工作方式? 但是由于模板函数全部都是匿名的,那么我怎样才能有效地连接或以某种方式使用它们呢?

检查ClientJade项目。

从他们的网站:

clientjade是一个命令行工具,可以将您的jade模板编译成客户端模板,以便在浏览器中使用。 它会自动包含你需要渲染模板的所有东西,不需要包含jade.js或者runtime.js。

 $ clientjade test1.jade test2.jade > templates.js 

然后在你的html中包含template.js文件。 要呈现模板,只需拨打电话:

 //jade.render(domNode, templateName, data); jade.render(document.getElementById('test1'), 'test1', { name: 'Bob' }); 

在看了Jadify和ClientJade之后,一路上遇到了一些问题(可能只是我错过了一些东西),我决定只是在服务器端编译模板。

我定义了一个Node模块(ExpressJS使用)来完成编译,并返回编译后的JS源文件(我使用了/js/templates.js )。

 fs = require "fs" jade = require "jade" async = require "async" # done callback will be passed (source, err) exports.compile = (done, templatesDir) -> js = "var Templates = {}; \n\n" # get all files in templates directory fs.readdir templatesDir, (err, files) -> # keep only ".jade" files jadeFiles = files.filter (file) -> file.substr(-5) == ".jade" # function to compile jade templates (appending to js source) compileTmpl = (file, doneCompile) -> # "test.jade" becomes "test" key = file.substr(0, file.indexOf(".")) filePath = templatesDir + file fs.readFile filePath, (err, src) -> # store js function source into Templates.{key} js += "Templates." + key + " = " + jade.compile(src, { debug: false, client: true }).toString() + "; \n\n" doneCompile(err) # foreach jadeFile, compile template, then write templates.js file async.forEach jadeFiles, compileTmpl, (err) -> done(js, err) 

我在客户端使用预编译的模板,包括templates.js并使用如下模板:

  • Templates.tmpl1()
  • Templates.tmpl2({ something: "Hello world", ... })

更多关于https://coderwall.com/p/hlojkw