1

Smarty{call}組み込み関数は、{function} タグで定義されたテンプレート関数を呼び出すことができます。ここで、プラグイン内の関数名しか知らないため、プラグイン関数内でテンプレート関数を呼び出す必要があります。

プラグイン機能:

<?php

$smarty->registerPlugin('function', 'form_label', 'renderFormLabel');

function renderFormLabel($form, \Smarty_Internal_Template $template) {

    // find out which function to call based on the available ones
    $function = lookupTemplateFunction($template);

    $args = $form->getVariables();

    // How to call the Smarty template function with the given $args?
    // $html = $template->smarty->???($args); 

    //return $html;
}

テンプレート:

<form action="submit.php" method="post">
    {form_label}
    ....
</form>

これはSmartyBundleでSymfony2 Formsをサポートするための取り組みです。各フォーム フラグメントは、Smarty 関数によって表されます。フォームのレンダリング方法の一部をカスタマイズするには、ユーザーは適切な関数をオーバーライドするだけです。

4

3 に答える 3

3

プラグイン内からテンプレート関数を呼び出すことができます。ただし、当初はこのオプションを計画していたため、現在、キャッシュが有効かどうかで API が異なります。これは、将来のリリースでも変更される可能性があります。

プラグイン内から {call name=test world='hallo'} のようなことをしたいとします:

if ($template->caching) {
   Smarty_Internal_Function_Call_Handler::call ('test',$template,array('world'=>'hallo'),$template->properties['nocache_hash'],false);
} else {
   smarty_template_function_test($template,array('world'=>'hallo'));
}

テンプレート関数は、プラグインを呼び出したテンプレートのコンテキストで呼び出されることに注意してください。呼び出し元のテンプレートで既知のすべてのテンプレート変数は、テンプレート関数内で自動的に認識されます。

テンプレート関数は HTML 出力を返しませんが、出力バッファーに直接入れます。

于 2012-02-05T19:47:15.177 に答える
2

最初の回答でもっと具体的であるべきでした。renderFormLabel のコードは次のようになります。

function renderFormLabel($form, \Smarty_Internal_Template $template) {

    // find out which function to call based on the available ones
    $function = lookupTemplateFunction($template);

    if ($template->caching) {
        Smarty_Internal_Function_Call_Handler::call ('test',$template,$form,$template->properties['nocache_hash'],false);
    } else {
        smarty_template_function_test($template,$form);
    }
}

この場合、$form 配列によって renderFormLabel プラグインに渡される属性 (パラメーター) は、テンプレート関数内のローカル テンプレート変数として表示されます。

于 2012-02-05T21:48:39.693 に答える
1

私があなたの必要性を理解できる限り、あなたは与えられた既知の引数で名前付きメソッドを呼び出したいと思います。

call_user_func_array次のような呼び出しを使用してみませんか:

call_user_func_array(array($template->smarty, $function), $args);
于 2012-02-05T20:01:43.653 に答える