Search code examples
javascriptpug

How can I concatenate an array in jade?


I'm trying to concatenate the items in an array c[x].topLevelIndustry by using a for loop:

 -var text="";
 -var y;
 script.
   for (y=0, y< c[x].topLevelIndustry.length, y++){
     text+=#{c[x].topLevelIndustry[y]} + ",";
   }
 p= text
  1. How can this be fixed, I've tried multiple things?
  2. What is the relation between variables in jade/javascript? If I set -var somevar then how do I make it available for jade?

Solution

  • Using the script tag prevents pug from running the code. Instead, it's passed on to the browser to execute client-side. Instead of a script tag, use an unbuffered code block.

    -
      var text = "";
      var y;
      for (y = 0, y < c[x].topLevelIndustry.length, y++){
        text += c[x].topLevelIndustry[y] + ",";
      }
    
    p #{text}
    

    The same result can be achieved more concisely using the .join() javascript method.

    p= c[x].topLevelIndustry.join()