Jade script: check if variable exists

320 views Asked by At

I want to optionally pass variables to my jade template, with pyjade==4.0.0, with some JavaScript to return defined variables (to locals().pageargs):

script(type='text/javascript').
    console.log("#{item_id}");

Which works perfect when item_id is defined., but... how to check if item_id exists and if not pass null?

File "/home/USER/anaconda3/lib/python3.6/site-packages/mako/runtime.py", line 226, in str raise NameError("Undefined") NameError: Undefined

attempts that do not work

console.log(`${'item_id' in locals()['pageargs']}`)

returns False or True, but:

console.log(`${'item_id' in locals()['pageargs'] ? locals()['pageargs']['item_id']: null}`)

Gives syntax errors.

1

There are 1 answers

0
gandreadis On

How about wrapping it in an if-conditional, like this?

script(type='text/javascript').
    var item_id = !{item_id};
    if (item_id) {
        console.log(`${'item_id' in locals()['pageargs'] ? locals()['pageargs']['item_id'] : null}`);
    }