How to check if an object exists when passing variables with jade

In Jade, you can pass an object to the client as follows

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 easier to check if this object exists before using it (and therefore, just try to determine var clientobj, if that is the case), but I hit my head trying to force it to do so.

For example:

res.render('mypage', {
  title: 'My Page'
});

Currently breaking this pattern, there needs to be some syntax to make this code more stable, of course.

+4
source share
1 answer

This piece of code should help.

script
    if myobject
        | var clientobj = !{JSON.stringify(myobject)}

, . () script. if myobject ... , Jade.

:

script.
    var clientid = #{myobject ? JSON.stringify(myobject) : "undefined"};

HTML, clientid undefined JavaScrip .

<script>var clientid = undefined;</script>

,

+4

Source: https://habr.com/ru/post/1528130/


All Articles