简体   繁体   English

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

[英]Access hbs variable in external js file

i am using hbs (express handlebars) to render a page. 我正在使用HBS(快速把手)来呈现页面。 i would like to access some variables in chat.hbs to an external file let us say chat.js(client side) 我想访问chat.hbs中的一些变量到一个外部文件,让我们说chat.js(客户端)

server side 服务器端

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

client side chat.hbs 客户端chat.hbs

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

I would like to access chatrrom id in an external js file for using socket.io 我想使用socket.io访问外部js文件中的chatrrom id

You can use ajax to fetch the template fetch('chat.hbs').then(r => r.text()); 您可以使用ajax来获取模板fetch('chat.hbs').then(r => r.text()); , you can share compiled function if that's what you want. ,则可以共享编译后的函数。 Then you need handlebars for client if that express one don't work in browser. 然后,如果表示客户端在浏览器中不起作用,则需要客户端的把手。

so you code should look like this if used with handlerbars.js: 因此,如果将其与handlerbars.js结合使用,则代码应如下所示:

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

and then you can render the it with: 然后可以使用以下命令呈现它:

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

inside hbs file 内部HBS文件

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

i tried this which worked inside client side js file 我尝试了在客户端js文件中工作的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM