Node JS Pass variables to pug template's JavaScript and html sections

爱⌒轻易说出口 提交于 2021-01-29 06:21:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!