Search code examples
node.jsexpressswig-template

Pass render args to next route


I am developing a NodeJS app using Express 3.0 with Swig as my template engine. What I would like to accomplish is the passing of render arguments to the next route. I want to this because I have certain site components which exist on every single page of my site (sidebar, navbar, footer, etc). Each and every one of these components has widgets and links that toggle on and off. Right now I am doing the following to toggle these widgets:

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'
      }
    }
  }
})

There is a lot of arguments there (within the widgets object) that I end up repeating numerous times within my code (once for each route). I was wondering if there is a way to pass args to the next route.


Solution

  • If the data is static (it doesn't change over the course of running your app), use app.locals to store it. Any data stored in there will automatically become available to any templates:

    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'
        } 
      }   
    }; 
    

    If the data does change, use res.locals instead. Any data stored there will also be available for any templates, but only during the lifetime of a single request. Any middleware can also access it (and change it if necessary).