構建模板我正在試圖製作一個使用ajax加載數據的現代網站,將它呈現在模板中並使用jQuery和pushstate來顯示它,再加上服務器端渲染,以便初始頁面加載速度很快,並且蜘蛛可以按預期抓取。當然,我讀了關於使用dust.js來實現這一目標的linkedin文章。如何在服務器和客戶端上使用dust.js
現在,dust.js聲稱具有以下優點:
可組合:設計師應該能夠打破呈現標記爲可管理的組成部分,並在運行時將這些組件。不需要靜態鏈接模板或在應用程序代碼中手動組合「佈局」。
格式不可知:雖然HTML生成和DOM操作在特定實例中很有用,但通用模板系統不應與特定的輸出格式綁定。
所以這聽起來不錯,但我怎麼才能真正實現我想要的?我製作了一個模板,可以在服務器上呈現完整的頁面,但它們使用塊和內聯部分 - 這意味着如果沒有包裝器存在,內部位就不能被渲染(它只是返回一個錯誤,表明它可以找不到包裝模板)。我不知道如何在應用程序代碼中編寫代碼(而不是上面的賣點#1)可以在客戶端避免。
我不明白上面的#2甚至意味着什麼。我想這意味着你得到的輸出爲一個字符串,並可以做任何你想要的東西?
該文檔與泥漿一樣清晰。
那麼我該怎麼做?這些天有沒有比dust.js更好的選擇?我是否要編寫模板,以便它們必須在應用程序代碼中組成?如果是這樣,我通過什麼機制在應用程序代碼中編寫它們?
好吧,既然已經無法理解我的問題(這本身是可以理解的),我只是把在一起的這種(未經測試)例如顯示問題:
包裝的模板:
<html>
<head><title>{+title/}</title>
{+styles/}
</head>
<body>
header header header
<div id="pagecontent">{+content/}</div>
footer footer footer
<script src="jquery"></script>
<script src="dust"></script>
<script src="see 'Client side script' below"></script>
</body>
</html>
'時間' 模板:
{>wrap/}
{<title}Time in millis{/title}
{<styles}
<style>
body {
background-color: {bgcolor};
}
</style>
{/styles}
{<content}
The time: {time}<br />
<a href="{link}">Switch format</a>
{/content}
服務器端代碼:
app.get('/millis',function(req,res) {
res.render('time',{millis:new Date().getTime(),link:'/time',bgcolor:'lightgreen'});
}
app.get('/time',function(req,res) {
res.render('time',{millis:new Date().toString(),link:'/millis',bgcolor:'lightpink'});
}
因此,服務器將呈現頁面正常,但客戶端呢?請繼續閱讀。
客戶端腳本:
//load the 'time' template into dust somewhere up here
$(function(){
$('a').click(function(e){
var newcontent;
switch($(this).attr('href')) {
case '/time':
//FAILS: can't find the wrapper. We need logic to get the title and styles from the template and fill it in in-place in the DOM
newcontent = dust.render('time',{millis:new Date().toString(),link:'/millis',bgcolor:'lightpink'});
case '/millis':
//FAILS: can't find the wrapper. We need logic to get the title and styles from the template and fill it in in-place in the DOM
newcontent = dust.render('time',{millis:new Date().getTime(),link:'/time',bgcolor:'lightgreen'});
default: return;
}
e.preventDefault();
$('#pagecontent').fadeOut(1000,function(){
//use pushstate and stuff here
$(this).html(newcontent);
$(this.fadeIn(1000);
});
});
});
我真的不明白你的問題是什麼。 – JAiro 2013-05-07 14:17:32
我添加了一個相當廣泛的例子 – jschall 2013-05-07 22:06:00
我寫了一篇文章回來。您可以查看: https://medium.com/@myusuf91/deploying-dustjs-in-a-spa-with-sailsjs-f8fb597814f5 – myusuf 2015-04-01 09:46:50