2013-01-21 22 views
1

我已經做了一些挖掘interweb周圍,但沒有什麼讓自己明顯。.htaccess重寫規則,以骨幹路由器轉換

我期待將一個自定義CMS與骨幹網結合起來,以便可以通過原始http請求或通過骨幹網中的「狀態」切換加載頁面。 CMS目前的重點是通過htaccess/mod-rewrite爲其路由/ url的自動化重寫規則,然而骨幹網爲其內部路由使用不同的格式化結構。

如果CMS可以將其重寫規則轉換爲主幹格式,那麼無論何時將頁面添加到CMS中,主幹都會意識到它並自動更新自身。因此,例如CMS喜歡這個頁面的加載輸出到全球地圖對象:

.... 
"contact"  => array(
     "key"  =>  "contact", 
     "url"  =>  "^(en|fr|de)/contact/$", 
     "type"  =>  "page", 
     "template" =>  "contact", 
     "method" =>  "contact", 
     "sitemap" =>  TRUE, 
     //other page config vars etc 
    ),//..and so on 
... 

有然後它寫入規則到的.htaccess像這樣一個解析器:

RewriteRule ^(en|fr|de)/contact$ index.php?page=contact&lang=$1&section=$2 

問題:

顯然backbone router format是有點不同,需要很多翻譯工作才能在PHP中完成,以便輸出一個很好的乾淨的路由器配置。 我不敢相信我是第一個遇到類似這樣的人,因爲這似乎是嘗試將骨幹應用程序集成到CMS的必要步驟。任何人都可以指出我翻譯這些字符串格式的方法嗎?也許我正在接近這個錯誤的方式?

非常感謝。

回答

1

骨幹支持使用router.route方法將路由定義爲正則表達式。 Apache mod_rewrite規則也是正則表達式。因此,諸如^(en|fr|de)/contact/$之類的表達式已經是有效的Backbone路由。

您不會說您是否已經有了一種機制,可以通過「站點地圖」服務或通過將數據引導至服務器上的HTML頁面來獲取路由配置到客戶端。但是,假設你可以輸出一個站點地圖對象是這樣的:

var sitemap = { 
    "contact": { 
    "url": "^(en|fr|de)/contact/$", 
    "type": "page" 
    //..other properties 
    }, 
    //...other pages 
} 

你可以通過遍歷站點地圖註冊路線:

var CMSRouter = Backbone.Router.extend({ 
    page: function(pageName, language) { 
     console.log(pageName); // -> "contact" 
     console.log(language); // -> "en" 
    } 
}); 

var router = new CMSRouter(); 
_.each(sitemap, function(entry, key) { 
    //handler method based on type ("page") 
    var handler = router[entry.type]; 

    //create a pre-applied callback function where the first argument 
    //is always set to the sitemap entry key ("contact"), and the 
    //rest of the arguments are filled from the capturing groups from 
    //the regular expression. 
    var callback = _.bind(handler, router, key); 

    //register route 
    router.route(new RegExp(entry.route), callback); 
}); 

Backbone.history.start(); 

這可能不會考慮到了很多的複雜性你的系統,但原則上它應該運作良好。如果您可以用更準確的要求編輯您的問題,我會很樂意編輯答案。

+0

哇..我完全錯過了骨幹可以使用正則表達式的路線!這是新的嗎?謝謝,我會給它一個旋轉 – Alex

+0

我太蠢了..我可以發誓,這並沒有總是這種情況..文件的第一行...謝謝! – Alex