我正在追踪Discover Meteor

由于某些原因,edit_post.html中的内容不会与{{#with post}}一起显示:

<template name="postEdit">
  {{#with post}}
    <form class="main">
      <div class="control-group">
        <label class="control-label" for="url">URL</label>
        <div class="controls">
          <input name="url" type="text" value="{{url}}" placeholder="Your URL"/>
        </div>
      </div>
     .
     .
     .
    </form>
  {{/with}}
</template>


post_edit.js的内容:

Template.postEdit.helpers({
  post: function() {
    return Posts.findOne(Session.get('currentPostId'));
  }
});

Template.postEdit.events({
  'submit form': function(e) {
    e.preventDefault();

    var currentPostId = Session.get('currentPostId');

    var postProperties = {
      url: $(e.target).find('[name=url]').val(),
      title: $(e.target).find('[name=title]').val()
    }

    Posts.update(currentPostId, {$set: postProperties}, function(error) {
      if (error) {
        // display the error to the user
        alert(error.reason);
      } else {
        Router.go('postPage', {_id: currentPostId});
      }
    });
  },

  'click .delete': function(e) {
    e.preventDefault();
      .
      .
      .
    }
  }
});


route.js:

this.route('postEdit', {
  path: '/posts/:_id/edit',
  data: function() { return Posts.findOne(this.params._id); }
});


如果删除{{#with post}},则显示模板。

我不确定这是书中的错误还是我做错了什么。我是流星初学者,所以我一无所知。

有什么建议解决这个问题吗?

最佳答案

模板助手post调用从未设置的Session变量,因此我认为findOne()返回虚假值。因此{{#with post}}可以正确显示模板。没有{{#with post}},您的模板就可以在路由器中显示data函数中的帖子。您正在调用findOne()两次,以查找相同的数据,但是这两种方法都可以获取模板所需的数据。

如果您想使用{{#with}},可以将route.js更改为:

this.route('postEdit', {
  path: '/posts/:_id/edit',
  before: function() { Session.set( "currentPostId", this.params._id ); }
});

关于javascript - 使用{{#with}}包装模板时,模板没有显示出来吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21655020/

10-11 15:29
查看更多