2012-12-11 189 views
4

我想在客戶端使用Jade模板和Backbone。我怎樣才能做到這一點?服務客戶端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 

注意管道(|)這些是爲了防止Jade試圖解釋/解析它們在服務器端。我如何消除這些?

UPDATE

也許我可以用jade --client標誌...但它給出了一個單一的編譯功能:例如

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(""); 
} 

這意味着我有爲每個模板有1個Jade /編譯的JS?我該如何使用它?另外我認爲很多JS文件是一種工作緩慢的方式?但是由於模板函數全部都是匿名的,那麼我怎樣纔能有效地連接或以某種方式使用它們?

回答

6

檢查ClientJade項目。

從他們的網站:

clientjade是一個命令行工具來編譯你的玉模板到客戶端模板在瀏覽器中使用。它將自動包含呈現模板所需的所有內容,無需包含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' }); 
3

看着Jadify和ClientJade,並且遇到沿途的幾個問題後......(也許它只是出頭我錯過了),我決定探索簡單地編譯服務器端的模板。

我定義了一個Node模塊(由ExpressJS使用),它執行編譯並返回編譯後的JS源代碼(我使用/js/templates.js)。

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

更多的https:// coderwall

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和使用模板使用在客戶端的預編譯模板。與/ W/hlojkw