【问题标题】:Call php function in view from mustache and pass a mustache array value into the function call从 mustache 调用视图中的 php 函数,并将 mustache 数组值传递给函数调用
【发布时间】:2025-12-24 08:15:11
【问题描述】:

我想将数组值传递给视图函数,以便它可以根据发送的值发回一些 HTML。我希望我的系统发送回文本区域、文本框或单选按钮。

在我的小胡子上,我有 {{#get_question}}{{type}}{{/get_question}},其中 type 可以具有来自 ["input","radio","comment"] 的任何值 我遇到的主要问题是如何调用此函数并传递参数。

我想要一个 php 函数 get_question 来提取 {{type}} 中传递的值,如果 type 不是文本,我想将 type 的值传递给我的部分调用 {{>}} 并动态加载由 {{type}} 表示的部分 我从 Kohana 论坛获得了这个代码示例:

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

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

从我的角度来看,我似乎无法让它工作,因为我必须将它包含在另一个 function(){} 块中。

我该怎么做?

【问题讨论】:

    标签: kohana-3.3 mustache.php


    【解决方案1】:

    这是一个令人头疼的问题,因为你正在与 Mustache 的基本原理作斗争:)

    这与“小胡子方式”有点倒退。与其试图通过 lambdas 硬塞逻辑,您应该将逻辑提取到您的视图/视图模型/模型中,并将您的模板限制为简单的部分和字符串插值。像这样的东西可以解决问题:

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

    然后每个问题视图/视图模型/模型将回答is_input()is_radio()is_comment()

    【讨论】:

    • 这正是我在将 is_input 或 is_radio 设置为 true/false 并将 partials 参数传递给视图时所做的。