簡體   English   中英

Nodejs骨干模板

[英]Nodejs Backbone Templates

我已經在Rails,requirejs和骨干網站上做了很多工作,並且知道如何在Rails中使用haml coffee模板。

App = new Backbone.Marionette.Application()



App.addInitializer (options) ->
  Backbone.history.start()
  alert "yay"


$ ->
 alert "yay"
 App.start() 

我如何在Node.js中做到這一點,我有一個Node.js應用程序,並且我在如何獲得模板來編譯客戶端方面陷入了僵局,我沒有陷入困境,任何模板引擎都可以做到,玉也可以,也可以強調。 這是一個很好的起點,因此我可以繼續在node.js中構建主干應用程序。

任何幫助表示贊賞!

我不建議將模板拖到客戶端並在那里進行編譯,正確的方法是使用一些框架,例如www.socketstream.com,它提供了您想要的內容以及更多信息。 如果您不贊成使用框架的快速而骯臟的解決方案,則可以在服務器上進行編譯並在客戶端上將其作為函數調用:

// compile.js 
var fs = require("fs")
    ,jade = require("jade");

exports.build = function(templatesDir) {
    var js = "var Templates = {}; \n\n";
    var files = fs.readdirSync(templatesDir);
    var jadeFiles = files.filter(function(file) {
        return file.substr(-5) === ".jade";
    });
    for(var i = 0; i < jadeFiles.length; ++i){
    var filePath, key;
    var file =  jadeFiles[i];
    key = file.substr(0, file.indexOf("."));
    filePath = templatesDir + file;
    var jadeSource =  fs.readFileSync(filePath);
    js += "Templates." + key + " = " + jade.compile(jadeSource, {
        debug: false,
        client: true
    }).toString() + "; \n\n";
}
return js;

};

// On the server.js
// Compile views
var viewsPath = path.join(__dirname, 'views/');
var generatedJs =  require('./compile').build(viewsPath);
var savePath = path.join(__dirname, 'public/js/lib/templates.js');
fs.writeFile(savePath, generatedJs, function (err) {
    if (err) throw err;
});

// Then on the client include js/lib/templates.js and use templates like this
FactSummaryView = Backbone.View.extend({
        template: Templates.issueSummary,
        render: function() {
            this.$el.html(this.template(this.model.toJSON()));

        return this;
    }
});

// Also add templates.js to nodemonignore if you're using nodemon
./public/js/lib/templates.js
/public/js/lib/templates.js

通常,您不編譯客戶端上的模板(希望模板直接在瀏覽器中編輯),而是在后端編譯並在瀏覽器中呈現

編譯模板

在此步驟中,您將模板源代碼編譯為包含渲染功能的JavaScript文件。

您可以在命令行上使用haml-coffee並在構建過程中創建腳本,也可以使用Haml-Coffee自述文件的集成部分中列出的項目。

Grunt是運行某些任務的流行解決方案,而使用Grunt-Haml,您無疑可以為您的項目提供靈活的構建解決方案。

渲染模板

要使用Marionette渲染模板,您需要確保模板渲染功能在客戶端上可用。 只需在開發人員工具中輸入配置的名稱空間,即可查看模板功能是否已注冊:

注冊模板功能

如果可以,則需要具有自定義模板渲染功能:

Backbone.Marionette.Renderer.render = (template, data) ->
  if JST[template]
    JST[template](data)
  else if _.isFunction(template)
    template(data)
  else
    console.error 'Template %s not found', template

現在,您只需定義視圖模板即可正確呈現它:

class App.Views.Login extends Backbone.Marionette.ItemView
  template: 'shared/_login'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM