Node JS 将变量传递给 pug 模板的 JavaScript 和 html 部分 [英] Node JS Pass variables to pug template's JavaScript and html sections

查看:53
本文介绍了Node JS 将变量传递给 pug 模板的 JavaScript 和 html 部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下路由,它将一系列变量传递给 pug 模板.

I have the following route and it passes a serires of variables to the pug template.

items.js 路由

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 }));
    }
});

在我的 editItem.pug 页面上,我需要将项目的变量传递到 javascript 部分和一系列输入框或标签.

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

推荐答案

要将 item.item_name 的值传递到 input 元素中,只需省略引号,这将在服务器上呈现:

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'...

这篇关于Node JS 将变量传递给 pug 模板的 JavaScript 和 html 部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆