构建模板我正在试图制作一个使用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