Search code examples
phpkohanamustachekohana-3.2

nested data in mustache template


I'm totaly new in mustache and this is my first project i'm trying it out. I use it with kohana 3.2 and Kostache module and PHP implementation of mustache.

I have a collection of sport tournaments and each of it has many events and each event has 3 entities that i call "outcome". My task is to show all of them in one table. Following template show how i need this table to be show.

{{#tournaments}}
    <h2>{{name}}</h2>
    <table class="event_list">
        {{#events.find_all}}
            <tr>
                <td>{{day}}</td>
            {{#outcomes.find_all}}
                <td class="outcome">{{name}}</td>
            {{/outcomes.find_all}}
            </tr>
        {{/events.find_all}}
    </table>
{{/tournaments}}

And now goes my problem and thus question. While showing "outcomes" i need to attach additional different classes to each . So i mean i have 3 "outcomes" for each event and thus i have 3 different CSS classes for each of them. But inside {{#outcomes.find_all}} loop i have no clue is it first entity or second or third. What can i do about this?

Trying to solve this I was thinking about using functions. I thought of adding function to this view's class that would render all events "outcomes" and this may look like this:

{{#tournaments}}
    <h2>{{name}}</h2>
    <table class="event_list">
        {{#events.find_all}}
            <tr>
                <td>{{day}}</td>
                {{print_outcomes}}
            </tr>
        {{/events.find_all}}
    </table>
{{/tournaments}}

But obviously i will need to pass collection of "outcomes" in that function and then i realized that i can't pass anything in that function. So how such problems solved in mustache?

Also if i have very simple function like this:

public function print_outcomes(){
    return "<td>aa</td>";
}

it will pass it trougth url_encode before put to output so that i will get

&lt;td&gt;aa&lt;/td&gt;

is that can be fixed?


Solution

  • You can try with function in your view model similar to this:

    public function outcomes()
    {
        $outcomes = ORM::factory('outcome')->find_all();
    
        $result = array();
    
        foreach ($outcomes as $outcome) 
        {
            $push = $outcome->object();
    
            $push['name']  = $outcome->name;
            $push['class'] = 'class_'.$outcome->name;
    
            $result[] = $push;
         } 
         return $result;
    }
    

    Then in your mustache you will have something like this:

    {{#outcomes}}
        <td class="{{class}}">{{name}}</td>
    {{/outcomes}}