问题
I have the following route and it passes a serires of variables to the pug template.
items.js route
router.get('/edit/:itemObjectId', async function(req, res, next) {
var itemObjectId = req.params.itemObjectId;
var equipmentCategoryArr = [];
var lifeExpectancyArr = [];
var businessUnitResponsibleArr = [];
var item = undefined;
try {
item = await db_item.getItem(itemObjectId);
// Where item["result"] is either undefined or a JavaScript Object. E.g. {"createdAt":"2018-11-07T04:07:44.587Z","updatedAt":"2018-11-07T04:25:18.526Z","item_name":"GM Portable","manufacturer":"GM"}
res.render('editItem', {
title: 'Edit item details', // Give a title to our page
item: item["result"],
equipmentCategoryArr: req.app.locals.equipmentCategoryArr,
lifeExpectancyArr: req.app.locals.lifeExpectancyArr,
businessUnitResponsibleArr: req.app.locals.businessUnitResponsibleArr
});
} catch (err) {
return Promise.reject(JSON.stringify({ "Error": err }));
}
});
On my editItem.pug
page, I need to pass the variables of an item into the javascript section and a series of input boxes or labels.
editItem.pug
extends layout
block extraScript
script.
$(document).ready(function(){
// HOW TO PASS THE ITEM HERE IN THE JAVASCRIPT SECTION
// FOR EXAMPLE:
// if (item == undefined) {
// alert("item not found");
//}
});
block content
.container
if (item != undefined)
.card
h1.text-center #{title}
form(method='POST' action='/items/addItem' class='needs-validation' enctype='multipart/form-data' novalidate)
.card
.card-header
i.icon-calendar
h4.panel-title Item Name
.card-body
.form-row
input#validationItemName.form-control(name='itemName' type='text' placeholder='Item name' required='')
div.invalid-feedback Item name is required!
// HOW TO PASS item.item_name TO THIS INPUT BOX
回答1:
To pass the value of item.item_name
into the input element just leave out the quotes and this will render on the server:
input#validationItemName.form-control(value= item.item_name name='itemName'...
来源:https://stackoverflow.com/questions/53254740/node-js-pass-variables-to-pug-templates-javascript-and-html-sections