在 hbs 视图中显示 Bookshelf.js 模型

Displaying Bookshelf.js model in hbs view

我是 Bookshelf.js 和 hbs 的新手,非常感谢您在以下方面的帮助:

我想用 Bookshelf.js 模型中的数据预填充 handlebars.js 视图表单。

hbs 不允许我使用 Bookshelf get 方法来获取所需的属性值:例如{{user.get(年龄)}}

我将模型转换为 JSON 但无法查询 hbs 中的特定 json 属性,例如{{user.age}}。

JSON

{"id":1,"fullName":"Mike","password":"password","email":"mike@email.com","age":38,"gender":"male","created_at":1432736718951,"updated_at":1432736718951}

我是否必须创建一个助手来从模型中提取属性值?


function getUserModel(req, res, next) {
  User.forge({id: req.user})
    .fetch()
    .then(function(user){
      req.model = user;
      return next()
    })
    .catch(function(err){
      debug("Error loading userId[%s]", req.user);
      return next(err);
    });
}

router.use(ensureAuthenticated)
  .use(getUserModel);

router.get('/', function handlePhotoUploadGet(req, res, next) {
  var callback = "http://" + req.headers.host + "/cloudinary_cors.html";
  var params = {return_delete_token: true, callback: callback,
    timestamp: cloudinary.utils.timestamp()};
  var dataFormData = cloudinary.utils.sign_request(params);

  res.render('photos/upload',
    { title: 'Photo upload',
      cloudinary: cloudinary,
      dataFormData: JSON.stringify(dataFormData),
      user: req.model } 
  );
});

<input type="text" name="age" aria-label="age" value="{{user.age}}" placeholder="age" class="radius {{#if errors.invalidAttributes.fullName}}error{{/if}}" />

<input type="radio" name="gender" value="male" aria-label="Male" id="male" {{#if_equal user.gender 'male'}}checked{{/if_equal}}><label for="male">Male</label>

为了回答这个问题,您需要提供服务器端代码,以查看您推送到响应的内容,以及客户端 html。请更新您的问题。

更新: 更改此行:

req.model = user; to this: req.model = user.toJSON();