最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pass handlebars variable to client js file - Stack Overflow

programmeradmin1浏览0评论

I'm building an app using node.js + express + handlebars and was looking for a way i can pass handlebars data from the server to client-side javascript files. For example:

//server.js

var person = {
    name: George,
    age: 32, 
}

res.render('../views/person', person)

I want to be able to use the person object on the client side such as:

//client.js

console.log(person.age);
console.log(person.name);

Can someone help?

Thanks!

I'm building an app using node.js + express + handlebars and was looking for a way i can pass handlebars data from the server to client-side javascript files. For example:

//server.js

var person = {
    name: George,
    age: 32, 
}

res.render('../views/person', person)

I want to be able to use the person object on the client side such as:

//client.js

console.log(person.age);
console.log(person.name);

Can someone help?

Thanks!

Share Improve this question asked Jan 25, 2016 at 16:16 Trung TranTrung Tran 13.8k48 gold badges126 silver badges209 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 1

try this

 res.render('../views/person', {person: person})

If you're passing more than just a few objects, I would remend building some sort of API around your client-server relationships using Express's routing ( http://expressjs./en/guide/routing.html )

// server
app.get('/person/a', function (req, res, next) {
  console.log('the response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send({person: {age: 30, name: "Bob", greeting: "hello"}});
});

and your client would then call those routes with the http module ( https://nodejs/api/http.html ):

// client
http.get({
  hostname: 'localhost',
  port: 80,
  path: 'person/a',
}, (res) => {
// Do stuff with response
})

You can pass data using JSON.Stringify() with {{{ }}}

There is Two Example

  1. use Stringify on render function
    • server
return res.render('../views/person', {person : JSON.Stringify(person)});
  • client
var person = {{{person}}}
console.log(person)
  1. Makes HBS Helper
    • server
hbs.hbs.registerHelper('convert', function (date) {
        if (!date) {
            return;
        }
        return JSON.stringify(date);
    });

return res.render('../views/person', {person : person});
  • client
var person = {{{convert person}}}
console.log(person)

I suggest number 2. It can be use on HTML and also Client javascript.

your route in the server could be like this

app.get("/",(req,res)=>{
  res.render("view_name",{val: 123,val2: "123"});
 });

then in your view file you could do something like this:

<script>
  console.log({{val}}); // if value it's number type
  console.log("{{val2}}");//in quotes if it's string type
  const val1 = {{val}};  
  const val2 = "{{val1}}";
<script/>
发布评论

评论列表(0)

  1. 暂无评论