Can we edit a mustache template in runtime?

254 Views Asked by At

Can I add new nodes to mustache template at run-time in PHP? Let's say below is a code where ProductDetails will contain few single products:

{{#ProductDetails}}
    {{#SingleProduct}} 
        {{OldDetail}}
    {{/SingleProduct}} 
{{/ProductDetails}}

I want to add a new node like {{NewDetail}} just after {{OldDetail}} through some function in run-time(i.e just before I am compiling the template as these templates have been shipped to customers in such a way that only code to compile can be changed but not the template)? I don't want to do string manipulation(customers created few new templates with above parameters present at least but the spacing may change & few new entries can be added by them around nodes). Does mustache library provide any functions for that?

1

There are 1 best solutions below

0
Chen Kuan Hung On

If I were you, I will try Lambdas.

Template.mustache will be like this:

{{#ProductDetails}}
    {{#SingleProduct}} 
        {{OldDetail}}
    {{/SingleProduct}} 
{{/ProductDetails}}

And codes will be like:

$Mustache = new Mustache_Engine(['loader' => new Mustache_Loader_FilesystemLoader($YOUR_TEMPLATE_FOLDER),]);
$Template   = $Mustache->loadTemplate('Template');

$OriginalOldDetail = '<h1>this is old detail</h1>';
echo $Template->Render([
    'ProductDetails'    => true, 
    'SingleProduct'     => true, 
    'OldDetail'         => function($text, Mustache_LambdaHelper $helper){
        // Render your original view first.
        $result = $helper->render($text);
        // Now you got your oldDetail, let's make your new detail.

        #do somthing and get $NewDetail;
        $NewDetail = $YourStuff;

        // If your NewDetail is some mustache format content and need to be render first.
        $result .= $help->render($NewDetail);

        // If is some content which not need to be render ? just apend on it.
        $result .= $NewDetail;

        return $result;
    }
]);

Hope that will help.

(English is not my first language so hope you can understand what I'm talking about.)