Question

I want to have a navigation bar, which is not hardcoded, but takes its items from a controller. My problem is, though, I don't want to set the navbar items in every page controller, but only in one file and use them for all pages, which have the same layout. So this is my layout.jade

doctype 5
html(lang='en')
  head
    meta(charset='UTF-8')
    meta(name='viewport', content='width=device-width')
    title= '™DreamTechnologies'
    block css
      link(rel='stylesheet', href='/components/bootstrap/dist/css/bootstrap.min.css')
      include styles.css
    block js
      script(src='http://localhost:35729/livereload.js')
  body
    nav.navbar.navbar-inverse(role="navigation")
      .container-fluid
        .navbar-header
          a.navbar-brand(href="/")
            |HOME
        .collapse.navbar-collapse
          ul.nav.navbar-nav
            each item in navitems
              li
                a(href=item.link)
                  =item.content
    div.page-header
      h1
        =title       
    block content

My question is how do I have to parse those navitems, so I have them on every page. For now I simply use this in every controller:

exports.index = function(req, res){
    res.render('home/index', {
        title: '™DreamTechnologies',
        navitems: [
            {link: 'this', content: 'that'},
            {link: 'secondLink', content: 'secondContent'}
        ]
    });
};

Of course, if I only write them here, I only have navigation on the home page...

Was it helpful?

Solution

You can use app.locals to pass common data to all templates. From the documentation:

app.locals

Application local variables are provided to all templates rendered within the application. This is useful for providing helper functions to templates, as well as app-level data.

The app.locals object is a JavaScript Object. The properties added to it will be exposed as local variables within the application.

You can incorporate this into your site in the following manner:

app.locals.navitems = [
  {link: 'this', content: 'that'},
  {link: 'secondLink', content: 'secondContent'}
];

app.get('/', function(req, res) {
  res.render('home/index', {
    title: '™DreamTechnologies'
  });
});

app.get('/about', function(req, res) {
  res.render('home/about', {
    title: '™DreamTechnologies - About'
  });
});

The navitems variable will now be available to all templates that are generated with res.render.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top