express-handlebars
express-handlebars copied to clipboard
How to insert different `link` and `script` for environment?
I need to insert scripts and styles which are environment related.
development: from local directory.
production: from CDN.
this should be from application level.
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>
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