Jade: Serving route-specific resources
Question
In my ./inc/footer.jade
I have a bunch of script tags. I would like to serve additional script only in one specific route. How to accomplish this?
In controllers I could do:
res.render('someTemplate', {
extraScript: true
});
and in footer.jade
- if (extraScript)
<script src="/script.js"></script>
but then I would have to include this 'extraScript' variable in every single route (set to false).
Solution
You can use typeof
to check whether a variable exists.
- if (typeof extraScript !== 'undefined')
<script src="/script.js"></script>
In this way, for all the routes that do not need the additional script, you simply don't pass in extraScript
, and then in the template, typeof extraScript !== undefined
will be evaluated to false
.
OTHER TIPS
The extraScript solution works, but I believe a better solution would be to use template inheritance (block and extends keywords) . This way you don't have to add logic and a local variable to your templates, and you can still keep things DRY in your jade markup.