admin管理员组

文章数量:1277899

I'm using hbs as a template engine along with html. This is my setting.

app.set('view engine', 'html');
app.engine('html', hbs.__express);

In my route.js

router.get('/home', isAuthenticated, function(req, res){
    res.render('home', { 
        user: data something });
});

In my home.html I want to use user variable not as a template but to do something

<script>
    var user = {{user}}; // It don't recognize user variable
    /* do something about user variable */
</script>

I'm using hbs as a template engine along with html. This is my setting.

app.set('view engine', 'html');
app.engine('html', hbs.__express);

In my route.js

router.get('/home', isAuthenticated, function(req, res){
    res.render('home', { 
        user: data something });
});

In my home.html I want to use user variable not as a template but to do something

<script>
    var user = {{user}}; // It don't recognize user variable
    /* do something about user variable */
</script>
Share Improve this question asked Apr 6, 2015 at 11:30 ChristogoroChristogoro 312 silver badges5 bronze badges 2
  • Try {{@user}} You're using Handlebars rendering engine, more info on correct syntax can be found here: github./donpark/hbs#exposing-locals-as-template-data – laggingreflex Commented Apr 6, 2015 at 11:44
  • @laggingreflex Thank you for your answer. In addition how can I convert that data into String. Now, It is var user = mydata; // It doesn't have a string quotation. I try using mydata.toString() and it doesn't work. – Christogoro Commented Apr 6, 2015 at 13:33
Add a ment  | 

4 Answers 4

Reset to default 9

Extending ting-y's answer.

If user is number or boolean:

var user = {{user}};

If user is a string:

var user = "{{user}}";

If user is an object or array, convert it into urlencoded JSON string and use:

var user = JSON.parse(decodeURI("{{user}}");

Standard approach

I like to you this more clean approach in rendering javascript variables using handlbars

json_utils.js

function tryParseJSON (jsonString){
    try {
        var o = JSON.parse(jsonString);

        if (o && typeof o === "object") {
            return o;
        }
    }
    catch (e) { }

    return null;
}


module.exports.safeJSONParse =tryParseJSON;

module.exports.encodeJSON =  function(obj) {

    obj = JSON.stringify(obj);

    return encodeURI(obj);
};

module.exports.decodeJSON = function(obj) {

    obj = decodeURI(obj);

    console.log(obj);

    return tryParseJSON(obj);
};

app.js

var express = require("express"),
    jsonUtils = require("./json_utils");
var app = express();

app.get("/",function(req,res) {

          var data = {
                 "name" : "John Doe",
                 "age" : 18,
                 "isAlive" : false,
                 "emergencyContacts" : [999999999,888888888,777777777]
          };

          res.render("home",{ "data" : jsonUtils.encodeJSON(data)});

});

home.handlebars

<script src="/utils_json_client.js"></script>
<script>
        var data = jsonDecode("{{data}}");
        console.log(data);
         // {
         //    "name" : "John Doe",
         //    "age" : 18,
         //    "isAlive" : false,
         //    "emergencyContacts" : [999999999,888888888,777777777]
         //}
<script>

try var user = "{{user}}";

if you user only contains string

You're using Handlebars rendering engine, the correct syntax would be {{@user}} more info

Surround them with quotes to cast those values into variables in javascript

<script>
    var user = "{{@user}}";
</script>

You should use like this if your variable is a object. If you just type var={{user}} it will give an error if you type var user='{{user}}' it will be a string.

But if it is an object you must initialize with [].

var user = ['{{user}}'];

本文标签: javascriptHow can I pass variable when render view to script tag in NodejsStack Overflow