I have a node file in which I am passing a variable to my pug file like this -
res.render("./products",
{pageTitle: "products",
prods: prods_arr});
This is my prods array-
[{ Types: "Electronic",Brand: "Apple", Products: [ "MacBook Pro", "MacBook Air", "Mac Mini"]},
{Types: "Electronic", Brand: "Dell", Products: [ "Inspioren", "Latitude"]},
{Types: "Electronic", Brand: "Samsung", Products: [ "Galaxy S20", "Galaxy S10"]}]
I can use my prods
array in my pug file to display its content. This is an example of my pug file-
select(name="type" onchange="change()")#type
option(value="Null") Type
for (products in prods) {
option(value=products.Type = #{procucts.Type}
}
select(name="brands")#brands
option(value="Null") Brand
But can't use it inside the script
tag. I want to loop through the prods
array using js inside pug so that I can add the values as options for the brands
selection box dynamically with an `onchange function. This is an example of how my js function should look like-
script.
function change() {
var type = document.getElementById("type").value;
var brand = document.getelementById("brands");
for (brands in prods) {
if (brands.Type == type) {
const brandOption = new Option(brands.Brand, brands.Brand);
brand.add(brandOption, undefined);
}
}
}
When I run !{JSON.stringify(prods)};
, my output is [object Object],[object Object],[object Object]
How can I use my prods array in pugs script tag??
CodePudding user response:
You have to stringify your array
script.
function change() {
var type = document.getElementById("type").value;
var brand = document.getelementById("brands");
for (brands in !{JSON.stringify(prods)}) {
if (brands.Type == type) {
const brandOption = new Option(brands.Brand, brands.Brand);
brand.add(brandOption, undefined);
}
}
}
!{JSON.stringify(prods)}
returns a verbatim JSON string of the array and you can use JSON as object/array literals in JavaScript.
The output is
<script>function change() {
var type = document.getElementById("type").value;
var brand = document.getelementById("brands");
for (brands in [{"Types":"Electronic","Brand":"Apple","Products":["MacBook Pro","MacBook Air","Mac Mini"]},{"Types":"Electronic","Brand":"Dell","Products":["Inspioren","Latitude"]},{"Types":"Electronic","Brand":"Samsung","Products":["Galaxy S20","Galaxy S10"]}]) {
if (brands.Type == type) {
const brandOption = new Option(brands.Brand, brands.Brand);
brand.add(brandOption, undefined);
}
}
}</script>
CodePudding user response:
You can't do it like that. prods
is a server-side variable, you have to tweak it in order to access it from client-side. The best suggestion would be not to do that. However, the tweak would be to render it as JSON string in the HTML before you send it to the client, and then read that in the client-side JS.
Example:
<meta name="prods" content="{{ JSON.stringify(prods) }}">
const prods = JSON.parse(document.querySelector('meta[name="prods"]').content);
console.log(prods);