2

I'm trying to add some EJS to a yaml file. I want to use a default value if a variable is not provided to EJS but can't figure out how. Here are two attempts, both of which fail with the following error message:

postgres_credentials_secret_name is not defined
    at eval (eval at compile (/Users/paymahn/code/goldsky/strick/infra/node_modules/ejs/lib/ejs.js:662:12), <anonymous>:107:17)
    at anonymous (/Users/paymahn/code/goldsky/strick/infra/node_modules/ejs/lib/ejs.js:692:17)
    at Object.exports.render (/Users/paymahn/code/goldsky/strick/infra/node_modules/ejs/lib/ejs.js:423:37)
    at Immediate.run (/Users/paymahn/code/goldsky/strick/infra/node_modules/ejs/bin/cli.js:201:20)
    at processImmediate (node:internal/timers:466:21) {
  path: ''
}

attempt 1:

                  <% if(postgres_credentials_secret_name) { %>
                  name: <%- postgres_credentials_secret_name %>
                  <% } else { %>
                  name: graph-node-postgres-credentials
                  <% } %>

attempt 2:

                  name: <%- postgres_credentials_secret_name || 'graph-node-postgres-credentials' %>

How can I get EJS to not complain if a variable is not provided since I'm providing a default value in templating logic itself.

Paymahn Moghadasian
  • 9,301
  • 13
  • 56
  • 94

1 Answers1

2

looks like you are not sending postgres_credentials_secret_name from your server so it is not defined in the template. You can use typeof postgres_credentials_secret_name and see if it is undefined. Or you could use locals.postgres_credentials_secret_name see this post

console.log(typeof postgres_credentials_secret_name)
console.log(typeof postgres_credentials_secret_name === 'undefined')
console.log(postgres_credentials_secret_name)
name: <%- typeof postgres_credentials_secret_name !== 'undefined' ? postgres_credentials_secret_name : 'graph-node-postgres-credentials' %>

alternatively you could use

name: <%- locals.postgres_credentials_secret_name ? postgres_credentials_secret_name : 'graph-node-postgres-credentials' %>

or even

name: <%- locals.postgres_credentials_secret_name || 'graph-node-postgres-credentials' %>

However, you could send something like an empty string then your approach would work

cmgchess
  • 7,996
  • 37
  • 44
  • 62
  • I find `if ("postgres_credentials_secret_name" in locals)` more readable, but that's just personal preference. – 3limin4t0r May 01 '23 at 11:58
  • @3limin4t0r if writing a ternary then `locals.postgres_credentials_secret_name ? postgres_credentials_secret_name : 'graph-node-postgres-credentials'` doesn't look too bad or maybe even `locals.postgres_credentials_secret_name || 'graph-node-postgres-credentials'` – cmgchess May 01 '23 at 12:00
  • The final suggestion is probably the cleanest. – 3limin4t0r May 01 '23 at 17:55