【问题标题】:Change View of Active ExpressJS Route -- Node.JS更改 Active ExpressJS 路由的视图 -- Node.JS
【发布时间】:2013-08-21 15:38:27
【问题描述】:

我有一条有效的快速路线——已经用模板定义了。

app.get('/route', function route(req, res) {
   db.get('db_ID', function compileAndRender(err, doc) {
      var stream = mu.compileAndRender('theme-file.extension', doc)
      stream.pipe(res)
   })

})

现在,我希望以后能够在应用程序中更改该路由的视图文件。我该怎么做?

基本上,我如何告诉 express '/route' 应该有一个新的 'theme-file.extension'?

【问题讨论】:

    标签: javascript node.js templates express url-routing


    【解决方案1】:

    好的,所以我只需要找出另一种思考问题的方式。我没有手动设置每条路由,而是使用参数变量来动态完成。

    代码如下:

    //Set up dynamic routes for all pages
    app.get('/:page_name', function(req, res) {
    
        db.get('pages_routes', function(err, doc) {
            var pure_routes = doc.pure_routes,
                 requested_page = req.params.page_name, 
                page_info = _.findWhere(pure_routes, { "url" : requested_page })
    
            if (page_info !== undefined) {
                db.get(page_info.id, function compileAndRender(err, doc) {
                    var stream = mu.compileAndRender(page_info.theme, doc)
                    stream.pipe(res)
                })
            } else {
                res.redirect('/index.html')
            }
        })
    })
    

    在我看来,这使代码更加简洁和易于使用。如果您有兴趣查看更多实际代码,您可以查看项目here(如果您发现可以改进的地方,请做出贡献!)。希望这对其他人有帮助!

    【讨论】:

      猜你喜欢
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      • 2016-08-08
      相关资源
      最近更新 更多