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

时间:2015-05-27 16:02:10

标签: express handlebars.js bookshelf.js

我是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>

1 个答案:

答案 0 :(得分:0)

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

更新: 改变这一行:

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