3

私が取り組んでいるサイトでは、AJAX を広範囲に使用してページ データを遅延読み込みし、Twitter スタイルのページングを行っています。PHP関数でHTML文字列を構築するよりもコーディングと保守が簡単になるため、テンプレートファイルを介してHTMLをレンダリングできるようにしたいと思っています。

DB からデータを取得し、tpl ファイルをロードするテーマ関数に渡す方法はありますか?


解決策: プログラムによる $node 出力で、テーマ('node', $node) と drupal_render($node->content) のどちらを決定するか

$node = node_load($nid);
$node_view = node_view($node);
echo drupal_render($node_view);
4

1 に答える 1

4

はい、できます。

Drupal 7 AJAX では、更新されてブラウザに返す必要があるフォーム要素を返す必要があるコールバック、または HTML を含む文字列、またはカスタム Ajax コマンドの配列を返す必要があります。

AJAX コマンドの 1 つはajax_command_html()で、テンプレートを使用してテーマ関数から返された HTML を挿入するために使用できます。

次のようなコードを作成できます。

function mymodule_ajax($form, &$form_state) {
  $form = array();
  $form['changethis'] = array(
    '#type' => 'select',
    '#options' => array(
      'one' => 'one',
      'two' => 'two',
      'three' => 'three',
    ),
    '#ajax' => array(
      'callback' => 'mymodule_ajax_callback',
      'wrapper' => 'replace_div',
     ),
  );

  // This entire form element will be replaced with an updated value.
  $form['html_div'] = array(
    '#type' => 'markup',
    '#prefix' => '<div id="replace_div">',
    '#suffix' => '</div>',
  );
  return $form;
}

function mymodule_ajax_callback($form, $form_state) {
  return theme('mymodule_ajax_output', array());
}

テーマ関数はhook_theme()、次のコードのように定義されています。

function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_ajax_output' => array(
      'variables' => array(/* the variables that will be passed to the template file */), 
      'template' => 'mymodule-ajax-output',
    ),  
  );
}

 

テンプレートのファイル名がテーマ関数の名前と一致する必要があることに注意してください。テーマ関数名にアンダースコアを使用する場合はハイフンを使用できますが、テンプレート ファイルの名前として「bar」を使用する「foo」という名前のテーマ関数を使用することはできません。
から報告されたテンプレート ファイルの名前には、テンプレート ファイルを検索hook_theme()するときに Drupal から追加される拡張子 (「.tpl.php」) が含まれていません。

于 2011-12-03T15:04:33.423 に答える