How can I display a default value for HTML attributes implemented using nunjucks?

66 Views Asked by At

I am a noob. I am using Prototype.KIT framework (https://design-system.service.gov.uk/components/) for creating interactive HTML prototypes using nunjucks. This is used in an HTML file with integrated nunjucks code.

Typically we assign certain attributes to an element on an HTML page using,

label: {
         text: "Some text"
       },
name: "someAttributeValue",
value: data['someAttributeValue'],

and on another page we are referring to that value and displaying it using,

key: {text: "Some text"},
value: {text: data['someAttributeValue']},

Variation

key: {text: "Some text"},
value: {text: data['someAttributeValue'] + "some text" + data['someOtherAttributeValue'] + "some text"},

How do I display a default value for example "0", in case, the someAttributeValue is empty?

I have tried these variations and it doesn't work,

value: data['someAttributeValue' || "0"]
value: data['someAttributeValue' = "0"]
value: data['someAttributeValue'] = "0"
1

There are 1 best solutions below

3
Tom On

If data['someAttributeValue'] returns null or undefined, you can default to "0" by using the below:

value: data['someAttributeValue'] || "0"