How to check if an object exists when passing variables with jade
javascript, node.js, pug
Solution
The following code snippet should help.
script
if myobject
| var clientobj = !{JSON.stringify(myobject)}
Please note that you should not put `.` (dot) at the end of `script` element. Otherwise `if myobject ...` will be considered as text and not Jade code.
Alternatively this should work too:
script.
var clientid = #{myobject ? JSON.stringify(myobject) : "undefined"};
In that case you will get following HTML code and you will have to handle `clientid` as `undefined` in your JavaScrip code in a page.
<script>var clientid = undefined;</script>
I hope that will help
Problem
In Jade you can pass through an object to the client like this Route: ``` res.render('mypage', { title: 'My Page', myobject : data }); ``` Jade Template: ``` extends layout block navbar include includes/navbar block top include includes/top block content script(src='/js/controllers/test-controller.js') script. var clientobj = !{JSON.stringify(myobject)} ``` But what if myobject does not exist? It seems like it would be the simplest thing to check if this object exists before using it (and therefore only try to define the var `clientobj` if it does) but I am banging my head here trying to get make this happen. Eg: ``` res.render('mypage', { title: 'My Page' }); ``` Will currently break the given template, there has to be some syntax to make this code more resilient, surely..