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.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Template Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

How do I add dynamic html class for every LI tag?


Go to End


5 Posts   2572 Views

Avatar
VPull

Community Member, 58 Posts

13 May 2015 at 7:22pm

I want to achieve some thing like this

<ul>
  <li class="row 4of5">
    Product Name: ABC
    Rating: 4 of 5
  </li>
  <li class="row 3of5">
    Product Name: PQR
    Rating: 3 of 5
  </li>
  <li class="row 3-5of5">
    Product Name: XYZ
    Rating: 3.5 of 5
  </li>
</ul>

How can I use value of Rating field as a class name for LI tag?

Avatar
wmk

Community Member, 87 Posts

13 May 2015 at 8:01pm

Hi VPull,

how is the rating generated? Could you paste the Dataobject representing the rating?

In general it's just making a getter method in the object which converts the current rating to a string.

e.g.

public function getRatingCSS() {
    return str_replace('.', '-', $this->CurrentRating . 'of5'); //converts also "3.5" to "3-5"
}

and in the template

<li class="$RatingCSS">
    Rating: $CurrentRating of 5
</li>

Avatar
VPull

Community Member, 58 Posts

13 May 2015 at 8:32pm

Edited: 13/05/2015 8:34pm

Thanks wmk but I am still confused about my code.

I am fetching product details by simply creating GetProductDetails() method in Page_Controller class. Because I want to display details on every page.

here is my GetProductDetails() method

  public function GetProductDetails(){
    $productList = DataObject::get('Products');    
    return $productList;
  }

Template code

<ul class="allproductslist">
  <% loop $GetProductDetails %>
  	<li class="row ">
      Product Name: $ProductName
      <br />
      Rating: $StarRate
    </li>  
  <% end_loop %>
</ul> 

Avatar
Pyromanik

Community Member, 419 Posts

13 May 2015 at 9:24pm

Edited: 13/05/2015 9:25pm

Going from your previous posts as a base:

class Products extends DataObject {
// <existing code>
// <wmk's getRatingCSS function above>
}

Then your template code as above:

<ul class="allproductslist">
  <% loop $GetProductDetails %>
  	<li class="row $RatingCSS"> <!-- NOTICE THE CHANGE HERE -->
      Product Name: $ProductName
      <br />
      Rating: $StarRate
    </li>  
  <% end_loop %>
</ul> 

Avatar
VPull

Community Member, 58 Posts

13 May 2015 at 9:36pm

You guys are simply Great,
all work fine as per required
Thanks for every thing :-)