worenga
worenga

Reputation: 5856

SilverStripe Templates: Displaying DataObject::Count without repeating

I have a Page, this Page has many, one or no comments. At one point i'd like to display only the number of comments without iterating through all of them. However due to translation it needs to be distinguished between two Plural Versions of the comment count, so a simple call of $Comment.Count is out. Since the translator component does not seem to have pluralization support whatsoever, i need to do it on the template level.

So far all i got is this:

<% if Comments %>
<% control Comments %>
<span class="comments">
 <% if Count == 1 %> ein Kommentar<% else %>$Count Kommentare<% end_if %></span>
<% end_control %>
<% end_if %>

This works but repeats Count-Times. Is there a workaround for this? Im aware of the possibility to create a function in my Page class like

function CommentCount(){
  return $this->Comments->Count();
}

but this feels a little bit tedious.

Upvotes: 3

Views: 2298

Answers (2)

Luke H
Luke H

Reputation: 3163

I made a litle Decorator as this kind of thing was annoying me.

It's perhaps a bit heavyweight for such a small thing, but you could easily extend it to provide what you need.

Basically it adds a method to DataObjectSet so you can do:

$Comments.Count $Comments.Plural(SingularWord, PluralWord)

Currently if you don't provide PluralWord it will try to guess a plural using typical english spelling changes.

Code is here: https://github.com/lingo/silverstripe-bits-and-bobs/blob/master/code/Pluraliser.php

Help and readme are here: https://github.com/lingo/silverstripe-bits-and-bobs/

Upvotes: 3

xeraa
xeraa

Reputation: 10859

From the top of my head - it should work, but I'm not sure if there wasn't a problem with statements like these:

<% if Comments.TotalItems == 1 %>Singular<% else %>Plural (inklusive 0)<% end_if %>

Alternatively you could build something like this (also untested, if it doesn't work, comment and I'll try to fix it):

<% if Comments %>
    <% control Comments %>
        <% if TotalItems == 1 %>
            Singular
        <% else %>
            Plural
        <% end_if %>
    <% end_control %>
<% else %>
    0
<% end_if %>

However, that's pretty ugly and bloated (besides having to repeat the plural piece for 0). I'd prefer a method like SingleComment(), returning true for 1 entry and false for 0 or more as it's IMHO clearer.

Upvotes: 2

Related Questions