2011-07-18 3 views
1

ノードのmustache.jsを使用してテンプレートとデータを分離したいと思います。可能であれば、fs.readFileを使用して明白ではありません。何かご意見は?ノードのmustache.jsでデータを区切る

私はあなたがjinjsを使用して試みることができるテンプレート

var mustache = require('mustache'); 
var fs = require('fs'); 
var http = require('http'); 

http.createServer(function (req, res) { 
    console.log('request recieved at ' + (new Date()).getTime()); 
    fs.readFile('./data.js', encoding='utf8',function(err, data) { 
    model2 = data; 
    console.log(model2); //logs the data.js as expected 
    }); 
    fs.readFile('./helloworld.html', function(err, template) { 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end(mustache.to_html(template.toString(),model2)); //model2 is not being passed in 
    }); 
}).listen(8081); 
+0

http://jade-lang.comをご覧になることをお勧めします。これはhttp://expressjs.comで使用できます。このようにして、きれいなコードを得ることができます。私はこれらの両方の製品が本当に良いと思う。 – Alfred

答えて

0

として配列モデルとhelloworld.htmlとしてdata.jsを使用しています。これは、非常に優れたPythonテンプレートシステムであるJinjaのポートです。 template.tplで

npm install jinjs 

:あなたのtemplate.jsで

I say : "{{ sentence }}" 

:あなたはこのようなNPMでそれをインストールすることができ

jinjs = require('jinjs'); 
jinjs.registerExtension('.tpl'); 
tpl = require('./template'); 
str = tpl.render ({sentence : 'Hello, World!'}); 
console.log(str); 

出力は次のようになります。

I say : "Hello, World!" 
+0

ありがとうございます - 私はjinjsを見ていきます。私はもっ​​と多くの玉の能力を使うように自分のコードを修正しました。実際には、データモデルをより互換性のあるものにするため、そしてJavaScriptを使用してデータを調整するのではなく、データモデルを変更することになりました。 – glgaines

関連する問題