[英]How do I create multi-page applications with Meteor?
我是Javascript的新手,只是出於好奇而開始擺弄Meteor。 讓我感到驚訝的是,似乎所有HTML內容都被合並到一個頁面中。
我懷疑有一種方法可以引入一些指向特殊頁面的URL處理。 似乎“todo”示例能夠通過某種Router
類來實現。 這是URL處理的“規范”方式嗎?
假設我可以處理URL,我將如何構建HTML代碼以顯示單獨的頁面? 在我的情況下,他們每個人都可以擁有完全獨立的數據集,因此根本不需要共享任何HTML代碼。
Jon Gold的答案過去是正確的,但截至Meteor 0.5.4 :
工作現在已轉移到Iron Router。 請考慮在新項目中使用IR而不是Router!
因此,目前的“規范”方式可能是使用IronRouter 。
據我所知,目前還沒有開箱即用的方法。
我建議做的是使用Backbone.js智能包。 Backbone.js帶有推送狀態路由器,如果用戶的瀏覽器不支持它,它將回退到哈希網址。
在你的meteor app目錄中輸入這個meteor add backbone
。
然后在客戶端代碼的某處創建一個Backbone.js路由器,如下所示:
var Router = Backbone.Router.extend({
routes: {
"": "main", //this will be http://your_domain/
"help": "help" // http://your_domain/help
},
main: function() {
// Your homepage code
// for example: Session.set('currentPage', 'homePage');
},
help: function() {
// Help page
}
});
var app = new Router;
Meteor.startup(function () {
Backbone.history.start({pushState: true});
});
然后在Handlebars模板中的某個位置,您可以創建一個幫助程序,該幫助程序將根據Session的“currentPage”中設置的值呈現頁面。
你可以在這里找到有關backbone.js路由器的更多信息: http : //backbonejs.org/#Router
此處還提供了有關如何在Metoer中創建Handlebars輔助方法的相關信息: http ://docs.meteor.com/#templates
希望這可以幫助。
Meteor-Router讓這很容易。 我一直在使用Telescope構建的一些應用程序中使用它作為一個很好的參考。 看看Telescope的router.js
要用它......
mrt add router
在client / router.js中:
Meteor.Router.add({
'/news': 'news', // renders template 'news'
'/about': function() {
if (Session.get('aboutUs')) {
return 'aboutUs'; //renders template 'aboutUs'
} else {
return 'aboutThem'; //renders template 'aboutThem'
}
},
'*': 'not_found'
});
在你的模板中......
<body>{{renderPage}}</body>
我發現了同樣的問題。 當代碼變大時,很難保持代碼清潔。
這是我解決這個問題的方法:
我將其他html頁面分開,就像我對其他Web框架一樣。 有一個index.html
,我存儲根html頁面。 然后對於每個大功能部分,我創建一個不同的模板並將其放在一個不同的html中。 然后流星將它們全部合並。 最后,我創建了一個名為operation
的會話變量,我在每次定義要顯示的內容。
這是一個簡單的例子
的index.html
<head>
<title>My app name</title>
</head>
<body>
{{> splash}}
{{> user}}
{{> debates}}
</body>
然后在splash.html中
<template name="splash">
{{#if showSplash}}
... your splash html code goes here...
{{/if}}
</template>
然后在user.html中
<template name="user">
{{#if showUser}}
... your user html code goes here...
{{/if}}
</template>
等等 ...
在javascript代碼中,然后我檢查何時使用Session變量打印每個模板,如下所示:
Template.splash.showSplash = function(){
return Session.get("operation") == 'showSplash';
}
最后,Backbone Router管理此Session變量
var DebateRouter = Backbone.Router.extend({
routes: {
"": "showSplash",
"user/:userId": "showUser",
"showDebates": "showDebates",
// ...
},
splash: function () {
Session.set('operation', 'showSplash');
this.navigate('/');
},
user: function (userId) {
Session.set('operation', 'showUser');
this.navigate('user/'+userId);
},
// etc...
});
我希望這種模式對其他Meteor開發人員有所幫助。
這是我對路由的hacky解決方案: https : //gist.github.com/3221138
只需將頁面名稱作為模板名稱,然后導航到/ {name}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.