访问外部js文件中的hbs变量

Access hbs variable in external js file

我正在使用 hbs (express handlebars) 呈现页面。 我想将 chat.hbs 中的一些变量访问到外部文件让我们说 chat.js(客户端)

服务器端

 res.render('chat', {chatroom,user}) 

客户端chat.hbs

    <div>
      <span id="chatroomid">{{chatroom._id}}</span>
      <span id="userid">{{user._id}}</span>
    </div>

我想在外部 js 文件中访问 c​​hatrrom id 以使用 socket.io

你可以使用ajax来获取模板fetch('chat.hbs').then(r => r.text());,如果你想要的话,你可以分享编译好的函数。如果那个快递在浏览器中不起作用,那么你需要客户端的把手。

因此,如果与 handlerbars.js 一起使用,您的代码应该如下所示:

var template = fetch('chat.hbs').then(r => r.text())
      .then(text => Handlebars.compile(text));

然后你可以渲染它:

template.then(fn => {
   var html = fn({chatroom: {_id: 10}, user: {_id: 20}});
   // update DOM with html
});

在 hbs 文件中

      <div hidden>
            <span id="chatroomid" chatroomid ="{{chatroom._id}}"></span>
        </div> 

我试过这个很管用 在客户端 js 文件中

 const $chatroomid = document.querySelector('#chatroomid')
 const chatroomId = $chatroomid.getAttribute('chatroomid')