【问题标题】:Is it possible to access a Handlebar variable through an external .js file?是否可以通过外部 .js 文件访问 Handlebar 变量?
【发布时间】:2020-05-02 16:53:16
【问题描述】:

尽管我们现在正在经历大流行,但我希望一切都好。我目前正在做一个学校项目,发现自己陷入了一个无休止的循环,试图弄清楚事情。我正在寻找一种方法,如何将路由处理程序传递给我的车把模板的数据访问到我单独的 javascript 文件。

请看下面的附加代码:

index.js(将变量传递给我的车把模板的路由处理程序)

app.get('/', function(req, res){
    if (req.session.loggedin){
        professorModel.aggregate([{ $sample: { size: 3 } }]).then(function(qvProfs) {
            reviewModel.find({}).populate('profRef').populate('studentRef').sort({_id:-1}).limit(10).exec(function(err,mostRecent) {
                collegeModel.find({}).exec(function(err, col){
                    var colleges = [];
                    var reviews = [];

                    col.forEach(function(document){
                        colleges.push(document.toObject());
                    });

                    mostRecent.forEach(function(document){
                        reviews.push(document.toObject());
                    });

                    res.render('frontend/home',{
                        studentRef: req.session.studentRef,
                        idNum: req.session.idNum,
                        colleges: colleges,
                        data: qvProfs,
                        review: reviews,
                        title: 'Home',
                    });
                });
            });
        });
    }
    else{
        res.redirect('/login')
    };
});

主布局('frontend/home'使用的布局)

<script src="/js/script.js"></script>

script.js(用于操作 html 的外部 .js 文件)

    var newReview = {
      profName: $('#revProfName').find(":selected").text(),
      profCourse: $('#revProfCourse').find(":selected").text(),
      studentRef: "{{req.session.studentRef}}",
      studentId: "{{req.session.idNum}}",
      reviewContent: $("textarea#revContent").val()
    };

每次我执行 console.log(newReview) 时,我总是得到 {{req.session.studentRef}} 和 {{req.session.idNum}} 而不是实际值。任何帮助将不胜感激。谢谢大家!

【问题讨论】:

    标签: javascript jquery node.js express express-handlebars


    【解决方案1】:

    好吧,看起来没有直接的方法让它工作,因为把手不解释单独的 js 文件,但这里有一个 hack。

    首先,您需要在视图文件中传递数据窗口范围。 如果您要传递 json/javascript 对象数据,请先注册一个辅助函数。

    有关此的更多信息可以找到here.

    hbs.registerHelper('json', function(context) {
        return JSON.stringify(context);
    });
    

    第二步:在视图文件中将数据添加到窗口范围。

    // if both variables you are sending are objects
    window.studentRef = JSON.parse('{{{json studentRef}}}');
    window.studentId = JSON.parse('{{{json studentRef}}}');
    // if the variables you are sending are int or string
    window.studentRef = {{studentRef}};
    window.studentId = "{{studentRef}}";
    

    然后您可以在窗口加载侦听器的 js 文件中的 windows 范围内访问这些。

    // inside your js file
    window.addEventListener('load', () => {
    
        var newReview = {
          profName: $('#revProfName').find(":selected").text(),
          profCourse: $('#revProfCourse').find(":selected").text(),
          studentRef: window.studentRef,
          studentId: window.studentId,
          reviewContent: $("textarea#revContent").val()
        };
    })
    

    希望你有实现它的想法。

    【讨论】:

    • 你好阿内斯!非常感谢您的解决方案!我能够提取数据并且它工作正常! studentId 实际上是一个整数值,当我尝试这样做时:window.studentId = {{studentRef}}; 它给了我一个未定义的值;但是,我能够通过用引号括起来来检索数据,因此它将 int 转换为字符串值。这个有什么解决方法吗?
    • 你可以使用函数parseInt ... window.studentid = parseInt("{{studentRef}}"),
    • 如果答案解决了您的问题,请考虑将其标记为解决方案。
    • 嗨阿内兹!你会碰巧知道我如何检索布尔值吗?它只是返回一个空字符。谢谢!
    • 现在了解您的问题.. 在发布问题之间,如果您的问题有用,您将得到解决方案。
    猜你喜欢
    • 2020-03-26
    • 2023-01-21
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多