开发者

Rendering a partial in a collection with Rails counter

I'm rendering a partial in a collection:

<%= render :partial => 'superlative', :collection => @profile.superlatives, :locals => {:superlative_count => @profile.superlatives.length} %>

Here is the partial:

<li class="superlative"><span title="<%= superlative.name %>">
  <%= superlative.body %>
</span>开发者_运维百科</li>

I want to render the collection so that:

  • Every item except the last renders with a comma and space at the end
  • The last item starts with and

So that the collection looks like this in its entirety: body, body, body, and body

I have some of that working with the code below but can't get the spacing right. Can someone help? Maybe there's also an easier way to do it? Thanks!

<% if superlative_counter + 1 == superlative_count %>
<li class="superlative"><span title="<%= superlative.name %>">
  <%= "and #{superlative.body}" %>
</span></li>
<% else %>
<li class="superlative"><span title="<%= superlative.name %>">
  <%= "#{superlative.body}," %>
</span></li>
<% end %>


It occurs to me there's another way to do this. Using CSS pseudo-elements you can just insert commas and "and" where you want them. Take a look in this fiddle. The major caveat here is that, at least in some browsers, if someone copy-and-pastes the list the pseudo-elements' content won't be included (i.e. they get "foo bar baz" even though they saw "foo, bar, and baz."

Assuming you want to do it in Ruby, though, what spacing issues are you seeing? I assume you're using CSS to turn a <ul> into a sentence--is there a particular reason you need each word to be inside an <li>? Your code looks fine, but I might be tempted to tweak it by moving those commas and 'and's outside the <span>s:

<% if superlative_counter + 1 == superlative_count %>
  <li class="superlative">
    and <span title="<%= superlative.name %>"><%= superlative.body %></span>
  </li>
<% else %>
  <li class="superlative">
    <span title="<%= superlative.name %>"><%= superlative.body %></span>,&nbsp;
  </li>
<% end %>

...but I'm not sure that'll have any effect on a spacing issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜