题
在我的./inc/footer.jade
我有一堆脚本标签。我想在一个特定的路线中提供额外的脚本。如何完成此操作?
在控制器中我可以做到:
.
res.render('someTemplate', {
extraScript: true
});
和footer.jade
.
- if (extraScript)
<script src="/script.js"></script>
但是,我必须在每条路线中包含这个'extrascript'变量(设置为false)。
解决方案
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
.
其他提示
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.