我们可以在运行时编辑胡子模板吗?

时间:2018-02-21 11:26:31

标签: php mustache mustache.php

我可以在PHP的运行时向mustache模板添加新节点吗?我们在下面说的是ProductDetails包含很少单个产品的代码:

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

我想在{{NewDetail}}之后通过运行时的某个函数添加{{OldDetail}}之类的新节点(即在我编译模板之前,因为这些模板已经发送给客户了只有编译代码可以改变而不是模板的方式)?我不想进行字符串操作(客户创建了少量新模板,其中至少存在上述参数,但间距可能会发生变化,并且节点周围可能会添加很少的新条目)。小胡子库是否为此提供了任何功能?

1 个答案:

答案 0 :(得分:0)

如果我是你,我会尝试Lambdas

Template.mustache将像这样:

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

代码将如下:

$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;
    }
]);

希望会有所帮助。

(英语不是我的母语,希望您能理解我在说什么。)