title: Express and Handlebars: Implementing multiple themes
body: <p>I and the team got a task to implement multiple themes for our project (keeping in mind that we have a single-theme project right now).</p>
  
  <p>By <strong>theme</strong> I don't mean just <strong>CSS</strong>, I mean different markup files, certain features for certain things, etc. (If you don't like the word 'theme' in this context don't use it, I hope you get the idea: some things need to be reused across the codebase, some things need to be specific to a <strong>theme</strong>). Overall, we have no problem of structuring it in a maintainable way and implementing the most of it, but we don't know how to make multiple <strong>express-handlebars</strong> configs, which we can switch based on <strong>certain factors</strong>.</p>
  
  <p>Right now we have a pretty standard <strong>express-handlebars</strong> project structure like such:</p>
  
  <pre><code>views/
   index
   layouts/
    main.hbs
   content.hbs
   whatever.hbs
  </code></pre>
  
  <p>What we want is something like this:</p>
  
  <pre><code>views/
   themes
    theme1
     layouts/
      main.hbs
     index.hbs
     content.hbs
    theme2
     layouts/
      main.hbs
     index
  </code></pre>
  
  <p>We use a pretty standard way to initialize <strong>express-handlebars</strong> in our app startup file like this:</p>
  
  <pre><code>var handlebars = exphbs.create({
    defaultLayout: 'main',
    extname: '.hbs',
    helpers: require('./server/hbsHelpers')
  });
  
  app.engine('.hbs', handlebars.engine);
  app.set('view engine', '.hbs');
  app.set('views', __dirname + '/views');
  </code></pre>
  
  <p>I was thinking to initialize several <strong>exphbs</strong> objects and switch them at runtime (request time) but this is not going to work since <code>app.set</code> would be an app-wide setting (long story short we host multiple websites with one app and can't afford change anything on app level, only on the express request level).</p>
  
  <p>Desired behaviour is something like this:</p>
  
  <pre><code>res.render(‘/theme1/file.hbs’);
  </code></pre>
  
  <p><em>looks like there's no problem just to render directly without a configuration, but then <strong>we also need to specify that handlebars needs to grab layouts and partials for a specific theme from a specific source</em></strong></p>
  
  <p><strong>or</strong></p>
  
  <pre><code>res.render(‘file.hbs’, { theme: ‘theme1’ });
  </code></pre>
  
  <p>We're using this variant of express handlebars – <a href="https://github.com/ericf/express-handlebars" rel="nofollow">https://github.com/ericf/express-handlebars</a>
  (May be you can advice an alternative that allows what I described above that we can interchange and not break a lot of things - our code base is pretty huge)?</p>
  
  <p>Any of your help, ideas or advice would be highly appreciated.</p>