ericf / express-handlebars

A Handlebars view engine for Express which doesn't suck.
BSD 3-Clause "New" or "Revised" License
2.32k stars 382 forks source link

How to insert different `link` and `script` for environment? #216

Open saeidalidadi opened 6 years ago

saeidalidadi commented 6 years ago

I need to insert scripts and styles which are environment related. development: from local directory. production: from CDN.

this should be from application level.

pietrofxq commented 6 years ago

First, create an if_eq helper:

const handlebars = require("express-handlebars")
const hbs = handlebars.create({
        defaultLayout: '',
        layoutsDir: '...',
        helpers: {
            "if_eq": function(a, b, options) {
                if (a == b) {
                    return options.fn(this)
                } else {
                    return options.inverse(this)
                }
            }
        }

You also need to add the process object to your locals:

let app = express()
app.locals.process = Object.assign({}, process)

Then in your template:

<body>
    {{{body}}}
    {{#if_eq process.env.NODE_ENV "development"}}
       <p>Development</p>
    {{else}}
      <p>Not development!</p>
      <script src="bundle.js"></script>
    {{/if_eq}}
</body>
bmcminn commented 6 years ago

Why wouldn't you just define the scripts in a .env file and let the app load that environment config via dotenv-safe or similar?

Then you just add the list of scripts into your default model definition that gets passed to the .render method.

https://www.npmjs.com/package/dotenv-safe