【问题标题】:Pass render args to next route将渲染参数传递给下一条路线
【发布时间】:2013-12-01 02:20:40
【问题描述】:

我正在使用 Express 3.0 和 Swig 作为我的模板引擎开发一个 NodeJS 应用程序。我想要完成的是将渲染参数传递给下一个路由。我想要这样做是因为我的网站的每个页面上都存在某些网站组件(侧边栏、导航栏、页脚等)。这些组件中的每一个都有可以打开和关闭的小部件和链接。现在我正在执行以下操作来切换这些小部件:

response.render('network.html', {
  activeTab: 'network',
  username: request.session.username,
  bread_current: 'Network',
  page_title: 'Your Network',
  page_subtitle: 'Mordrum',
  widgets: {
    navbar: {
      chats: {
        enabled: true,
        color: 'blue',
        icon: 'chatbubble'
      }, messages: {
        enabled: true,
        color: 'red',
        icon: 'mail'
      }, users: {
        enabled: true,
        color: 'green',
        icon: 'person'
      }
    }
  }
})

那里有很多参数(在小部件对象中),我最终在我的代码中重复了很多次(每个路由一次)。我想知道是否有办法将 args 传递到下一条路线。

【问题讨论】:

    标签: node.js express swig-template


    【解决方案1】:

    如果数据是静态的(它不会在运行您的应用程序的过程中发生变化),请使用app.locals 来存储它。存储在其中的任何数据都将自动可供任何模板使用:

    app.locals.widgets = {
      navbar: {
        chats: {
          enabled: true,
          color: 'blue',
          icon: 'chatbubble'
        }, messages: {
          enabled: true,
          color: 'red',
          icon: 'mail'
        }, users: {
          enabled: true,
          color: 'green',
          icon: 'person'
        } 
      }   
    }; 
    

    如果数据确实发生变化,请改用res.locals。存储在那里的任何数据也可用于任何模板,但仅在单个请求的生命周期内。任何中间件也可以访问它(并在必要时更改它)。

    【讨论】:

    • 非常感谢,这正是我所需要的!
    【解决方案2】:

    这样做的快速方法是将它们设置为res。大概你有一个Widget1 中间件。这将设置res.widget1.options,然后调用next()。然后另一个中间件会设置res.widget2.options,以此类推。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 2011-11-11
      • 2015-02-14
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      相关资源
      最近更新 更多