kohana-3.3mustache.php

Call php function in view from mustache and pass a mustache array value into the function call


I would like to pass an array value to a view function so that it can send back some HTML based on that value sent. I want my system to either send back textarea, textbox or radio button.

On my mustache I have {{#get_question}}{{type}}{{/get_question}} where type can have any value from ["input","radio","comment"] The main headache I have is how to call this function and pass the parameter.

I would like to have a php function get_question which extracts the value passed in {{type}}, if type is not text, I would like to pass the value of type to my partial call {{>}} and dynamically load the partial represented by the {{type}} I got this code sample from Kohana forums:

Hello, {{#caps }}{{ text }}{{/ caps }}!

    $m = new Mustache_Engine(array(
        'helpers' => array(
            'caps' => function() {return function($text, $m) {
                  return strtoupper($m->render($text));
            }}
        )
    ));

I can't seem to get it to work from my view since I have to enclose it in another function(){} block.

How do I go about this?


Solution

  • It's a headache because you're fighting against the fundamentals of Mustache :)

    This is a bit backwards from the "Mustache way". Instead of trying to shoehorn in logic via lambdas, you should extract the logic into your view/viewmodel/model, and limit your template to simple sections and string interpolations. Something like this would do the trick:

    {{# questions }}
      {{# is_input }}{{> input }}{{/ is_input }}
      {{# is_radio }}{{> radio }}{{/ is_radio }}
      {{# is_comment }}{{> comment }}{{/ is_comment }}
    {{/ questions }}
    

    Then each question view/viewmodel/model would answer to is_input(), is_radio() and is_comment().