Set temporary variable and reuse it further down in pug template

Viewed 1242

I am trying to pass along some values from my nodejs/express backend into the template (using res.render({...})), store it in some variables, then pass it further up until the front end (The usecase is that I need to do some mild calculation on the passed values and stored them in some intermediate variables)

I know I can do this in the pug file

block append script
  script.
    const foo = parseInt(#{stat.get('fooStat')}, 10);

But then later it seems that I can not refer to this later in my pug template, say here

  span #{foo}

The value is empty, I guess because it is undefined... What's the usual way to accomplish that.

1 Answers

Adding the period after the script tag signals to pug that its contents should be treated as plain text. This is handy when you want to write javascript for client-side consumption, but any variables declared are inaccessible to pug.

script.
  const foo = 10;

span #{foo} // foo is undefined here

If you want to define a variable that pug can use later in the template, do so using unbuffered code.

- const foo = 10

span #{foo} // renders <span>10</span>
Related