SkydersZ
SkydersZ

Reputation: 173

How return the result of a function from an external javascript script to a pug file?

I'm currently working on a little project which use pug (I discovered it just yesterday).

Here is my configuration:

file1.pug

- let resultArray = oldArray;

input(
  type='button'
  name='resultButton'
  placeholder='Click me...'
  onclick="addNumber(resultArray)"
 )

script
  include scripts/search_script.js

externalScript.js

function getTotal(resultArray) {

  let result = 0;
  let newArray = [];

  for(let i = 0; i < resultArray.length; i++){
    result += resultArray[i]; 
  }  

  newArray.push(result);

  return newArray;
}

It's just a little (weird) example of what I did.

The thing is, I was wondering if the value of resultArray which is in my file1.pug can be replaced by the value returned from the method getTotal() in my externalScript.js?

Upvotes: 2

Views: 455

Answers (1)

Sean
Sean

Reputation: 8026

Pug won't have access to javascript included inside a script tag, which will only run in browser. If you want to use the getTotal() function in Pug, you could include it in an unbuffered code block in your Pug file like this:

-
  function getTotal(resultArray) {

    let result = 0;
    let newArray = [];

    for (let i = 0; i < resultArray.length; i++) {
      result += resultArray[i]; 
    }

    newArray.push(result);

    return newArray;
  }

Upvotes: 2

Related Questions