[英]How to pass an array variable from javascript to a pug file?
我目前正在學習網絡開發。 我正在嘗試使用pug和javascript動態填充服務器端的頁面。 我的帕格代碼如下
#products-list.products
- var product_list = #{product_list}
-if(product_list)
each product in product_list
+product_element(product['name'],product['price'],product['image'])
product_element是一個mixin,其代碼如下
mixin product_element(name,prod_price,image)
a(href='./produits/${product.id}' title='En savoir plus...')
h2= name
img(alt='product' src='./assets/img/'+image)
p.price= prod_price
small Prix
|
我的JavaScript代碼在這里
router.get("/produits", (req, res) => {dataBase.getProducts(null,null).then(
(products)=>{
if(products)
{
console.log('Get /produits sending..');
res.render("products", {
titre: "OnlineShop - Produits",
products_count: products.length+" produits",
products_list:JSON.stringify(products)
});
}
}).catch(
(err)=>{
});});
我的請求后得到了一個有效的產品列表,我的問題是在頁面渲染期間出現的,看來我沒有正確地將數據鏈接到pug文件。 我到處搜索,但沒有找到答案。
當前,我有此錯誤:SyntaxError:意外的字符'#'
首先,讓我們從模板開始。 您不必在模板內重新聲明變量,它們已經在您那里了。 還要注意,如果變量不存在,則each
循環將不會執行,也不會輸出任何內容。
嘗試以下方法:
#products-list.products
each product in product_list
+product_element(product['name'],product['price'],product['image'])
然后,mixin內部也會出現問題。 它期望看到四個變量輸入,但是第一行調用product.id
,它不是mixin定義中列出的變量之一。 最好傳入整個產品對象,而不是將其分成單獨的變量:
mixin product_element(product)
a(href= './produits/' + product.id title='En savoir plus...')
h2= product.name
img(alt='product' src='./assets/img/'+ product.image)
p.price= product.price
small Prix
這會將您的模板更改為此:
#products-list.products
each product in product_list
+product_element(product)
最后,您需要將整個產品列表從路線傳遞到模板中。 只需將整個結果集從數據庫傳遞到模板中,如下所示:
router.get("/produits", (req, res) => {dataBase.getProducts(null,null).then(
(products)=>{
if(products)
{
console.log('Get /produits sending..');
res.render("products", { "product_list": products });
}
}).catch(
(err)=>{
});});
這會將產品數組傳遞到名為“ product_list”的變量中的模板。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.