3.7 Templates -- Links

一、The {{link-to}} Helper

1. 使用{{link-to}}创建一个指向route的链接:

app/router.js

Router.map(function() {
  this.route("photos", function(){
    this.route("edit", { path: "/:photo_id" });
  });
});

app/templates/photos.hbs

<ul>
  {{#each photos as |photo|}}
    <li>{{#link-to 'photos.edit' photo}}{{photo.title}}{{/link-to}}</li>
  {{/each}}
</ul>

如果photos templatemodel是一个三张照片的集合,HTML:

<ul>
  <li><a href="/photos/1">Happy Kittens</a></li>
  <li><a href="/photos/2">Puppy Running</a></li>
  <li><a href="/photos/3">Mountain Landscape</a></li>
</ul>

2. {{link-to}}有一个或者两个参数:

  • 路由的名字。在例子中,就是index, photos或者photos.edit
  • 动态段dynamic segment的大多数模型,默认的,Ember将会使用相应对象的id属性的值替换每个段。在上面的例子中,第二个参数就是每个photo对象,id属性被用来填充对应字段,无论是1,2,3。如果没有model被传递给helper,你可以提供明确的值来代替。
  • app/templates/photo.hbs
  • {{#link-to 'photos.photo.edit' 1}}
      First Photo Ever
    {{/link-to}}
  • 当被渲染的链接匹配当前路由,并且同一个对象实例被传递到helper,然后这个link会添加class="active"属性。例如,如果URL是/photos/2,上面第一个例子会被渲染为:
  • <ul>
      <li><a href="/photos/1">Happy Kittens</a></li>
      <li><a href="/photos/2" class="active">Puppy Running</a></li>
      <li><a href="/photos/3">Mountain Landscape</a></li>
    </ul>  

二、Example for Multiple Segments

如果路由是嵌套的,你可以为每一个动态字段提供一个模型或者一个标识符。

app/router.js

Router.map(function() {
  this.route("photos", function(){
    this.route("photo", { path: "/:photo_id" }, function(){
      this.route("comments");
      this.route("comment", { path: "/comments/:comment_id" });
    });
  });
});

app/templates/photo/index.hbs

<div class="photo">
  {{body}}
</div>

<p>{{#link-to 'photos.photo.comment' primaryComment}}Main Comment{{/link-to}}</p>

如果你仅仅指定一个模型,它将代表最内层的动态段:comment_id:photo_id字段会使用当前的photo。

可选择的,你可以传递一个photoid和一个comment

app/templates/photo/index.hbs

<p>
  {{#link-to 'photo.comment' 5 primaryComment}}
    Main Comment for the Next Photo
  {{/link-to}}
</p>
  • 在上面例子中,PhotoRoutemodel hook将会使用params.photo_id=5运行。CommentRoutemodel hook不会运行直到你为comment字段提供一个对象。commentid将会根据CommentRoute的 序列化钩子方法填充URL。

三、Using link-to as An Inline Helper

除了作为一个块表达式之外,通过指定链接文本作为helper的第一个参数,link-to helper也可以在inline form中被使用:

A link in {{#link-to 'index'}}Block Expression Form{{/link-to}},
and a link in {{link-to 'Inline Form' 'index'}}.

输出:

A link in <a href='/'>Block Expression Form</a>,
and a link in <a href='/'>Inline Form</a>.

四、Adding Additional Attributes on A Link

当生成一个链接时你可能希望设置为它额外的属性。你可以使用额外的参数这样做:

<p>
  {{link-to 'Edit this photo' 'photo.edit' photo class="btn btn-primary"}}
</p>

许多通用的HTML属性你都可以使用例如class。当添加类名时,Ember还将应用标准的ember-view和可能的active类名。

五、Replacing History Entries

当在路由之间跳转时,link-to默认的形式是在浏览器的历史中增加条目。然而,在浏览器历史记录中你可以使用replace=true替换当前条目。

<p>
  {{#link-to 'photo.comment' 5 primaryComment replace=true}}
    Main Comment for the Next Photo
  {{/link-to}}
</p>
原文地址:https://www.cnblogs.com/sunshineground/p/5153011.html