ddy250
ddy250

Reputation: 311

How to pass an array as an argument from pug to JS?

I'm trying to pass an array c[x].topLevelIndustry as an argument to a function in pug, my pug code is:

script.
  function myFunction(z) {
    var y = document.getElementById("demo");
    y.innerHTML =z.join();
  }


   myFunction(c[x].topLevelIndustry)
   p#demo

c is passed via index.js, my JS code is:

res.render('index', { title: 'About', c:c, d:d, e:e});

When I pass ['banana', 'apple'] as the argument then everything works, so I suppose the syntax is wrong.

Upvotes: 2

Views: 1062

Answers (1)

Andrew Koster
Andrew Koster

Reputation: 1835

Let's say this is the server-side variable that you want to pass in to your client-side Javascript:

const veryImportantObject = {foo: 'bar', number: 666};

Your're passing it into Pug as a template variable like this:

pug.renderFile(__dirname + '/Example.pug', {

    myPugTemplateVar: veryImportantObject,
});

From your Pug template, you can pass it along to the client side unescaped by using the !{} interpolation syntax. In order to avoid getting a useless toString() output like [Object object] or whatever, use JSON.

script(type="text/javascript").
    myPugTemplateVarInTheBrowser = !{JSON.stringify(myPugTemplateVar)};

This will output an HTML template with something like this:

<script type="text/javascript">
    myPugTemplateVarInTheBrowser = {foo: 'bar', number: 666};
</script>

Upvotes: 1

Related Questions