Create a <li class=“active”> around an active {{linkTo}}

 ̄綄美尐妖づ 提交于 2019-12-12 08:57:18

问题


What is the cleanest way to get <li class="active"> for the active page in the following Ember app?

index.html

<script type="text/x-handlebars">
  <ul class="nav">
    <li>{{#linkTo 'ping'}}Ping{{/linkTo}}</li>
    <li>{{#linkTo 'pong'}}Pong{{/linkTo}}</li>
  </ul>
</script>

app.js

App = Ember.Application.create()

App.Router.map(function() {
  this.route("ping", { path: "/ping" });
  this.route("pong", { path: "/pong" });
});

回答1:


replace in your template the li tags like so:

index.html

<script type="text/x-handlebars">
  <ul class="nav">
    {{#linkTo 'ping' tagName="li"}}Ping{{/linkTo}}
    {{#linkTo 'pong' tagName="li"}}Pong{{/linkTo}}
  </ul>
</script>

the {{linkTo}} with the tagName specified will apply a css class name of 'active' automatically when the application's current route matches the supplied route name.

example, when your app url is at /#/ping the resulting markup would be something like:

 ...
 <li class="active">Ping</li>
 ...

Or you create a custom view

App.ItemView = Ember.View.extend({
  tagName: 'li',
  classNameBindings: ['active'],

  active: function() {
    return this.get('childViews.firstObject.active');
  }.property()
});

and then use it like so

 <script type="text/x-handlebars">
   <ul class="nav">
   {{#view App.ItemView}}
     {{#linkTo 'ping'}}Ping{{/linkTo}}
   {{/view}}
   {{#view App.ItemView}}
     {{#linkTo 'pong'}}Pong{{/linkTo}}
   {{/view}}
   </ul>
 </script>

some css to see it actually working

li a {
  color: #000; 
}
li a.active {
  color: #f00;
}

hope it helps




回答2:


This workaround did it for me:

{{#linkTo  'menus.search' tagName='li' href=false}}
    {{#linkTo 'menus.search'}}
        <i class="icon-search"></i>
    {{/linkTo}}
{{/linkTo}}

It creates an li element containing an anchor element. And both will be updated with the "active" class when the route is active.




回答3:


Just nest the {{link-to}} with a tagName on the outer one. This will set an active class on both the outer <li> and the inner <a> tag.

{{#link-to "ping" tagName="li"}}
    {{#link-to "ping"}}ping{{/link-to}}
{{/link-to}}

{{#link-to "pong" tagName="li"}}
    {{#link-to "pong"}}pong{{/link-to}}
{{/link-to}}


来源:https://stackoverflow.com/questions/16380523/create-a-li-class-active-around-an-active-linkto

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!