Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Template Questions

Difficulties with If-Statements


Reply

6 Posts   3904 Views

Avatar
John Silver

15 September 2009 at 12:42am Community Member, 10 Posts

I tried to give all pages that don't have any children the class attribute "leaf".

After experimenting quite some time with this:

<div id="page"<% if Children.TotalItems < 1 %> class="leaf"<% end_if %>>
or
<div id="page"<% if !Children %> class="leaf"<% end_if %>>
or
<div id="page"<% if Children.TotalItems == 0 %> class="leaf"<% end_if %>>

which all gave a "Parse error", I finally had to use this very odd method to get it to work:

<div id="page"<% if Children.TotalItems %><% else %> class="leaf"<% end_if %>>

This doesn't seem right. What did I do wrong? There must be an easier way to accomplish this.
Any thoughts? Is it not possible to do comparisons in Silverstripe templates?

Avatar
Pigeon

15 September 2009 at 1:01am Community Member, 243 Posts

Hi John,

The template language isn't like PHP, so doing:

<div id="page"<% if Children.TotalItems = 0 %> class="leaf"<% end_if %>>

Should work (note only ONE '=')

Hope that helps!

Avatar
John Silver

16 September 2009 at 4:13am Community Member, 10 Posts

Thanks for the reply, but that doesn't work either. It doesn't throw a parse error though - the statement is simply ignored.

Avatar
Pigeon

18 September 2009 at 11:47am Community Member, 243 Posts

So if ... = 0 and if != 0 are both ignored?

Avatar
Willr

18 September 2009 at 3:46pm Forum Moderator, 5511 Posts

Try <% if Children %><% else %>class="leaf"<% end_if %> which should work. Saying that I would have thought Children.TotalItems would have worked.

Just to clear up the others

<% if !Children %> Will not work - negation is not supported
<% if Children.TotalItems == 0 %> Will not work. SSViewer uses = not == as it doesn't have assignment.

Avatar
John Silver

18 September 2009 at 7:56pm (Last edited: 18 September 2009 8:00pm), Community Member, 10 Posts

My solution now:

I put this in my page class

   public function isLeaf() {
      return $this->Children()->TotalItems() == 0;
   }

and this in my page.ss:

<div id="page"<% if isLeaf %> class="leaf"<% end_if %>>

Now the code looks clean. I'm not sure that this is the "right" way to do it, as I'm not really an expert with this MVC thing. Should this be in the Controller or somewhere else?

I still think negations and comparisons should be possible in the template. Is this just not the way things are done with SilverStripe or will this functionality be added in the future?
It seems very odd to me to always write something like

<% if Control %><% else %>Output<% end_if %>

instead of

<% if !Control %>Output<% end_if %>

Oh and for the

<% if Children.TotalItems = 0 %> class="leaf"<% end_if %>


- tried it again to make sure. Doesn't work.