2011-12-02 20 views
3

我正在使用的網站廣泛使用AJAX來延遲加載頁面數據並執行Twitter風格的分頁。我真的希望能夠通過模板文件呈現HTML,因爲它比在PHP函數中構建HTML字符串更容易編碼和維護。是否可以使用模板文件爲AJAX調用返回HTML?

是否有某種方法從數據庫獲取數據並將其傳遞給加載tpl文件的主題函數?


解決方案: How do I decide between theme('node', $node) and drupal_render($node->content) for programmatic $node output

$node = node_load($nid); 
$node_view = node_view($node); 
echo drupal_render($node_view); 
+0

你使用的是D7 Ajax框架還是你自己的調用? – corbacho

+0

我用我自己的電話,我確實有這個工作成功;) – SomethingOn

回答

4

是的,可以。

Drupal 7 AJAX需要一個回調,它需要返回已更新並需要返回給瀏覽器的表單元素,或者包含HTML的字符串或自定義Ajax命令數組。

其中一個AJAX命令是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', 
    ), 
); 
} 

 

要注意的是,模板文件名必須與主題功能的名稱匹配;可以使用連字符,其中主題函數名稱使用下劃線,但不能使用名爲「foo」的主題函數使用「bar」作爲模板文件的名稱。
hook_theme()報告的模板文件的名稱不包括在查找模板文件時從Drupal添加的擴展名(「.tpl.php」)。

+0

感謝您的迴應!我會明天檢查一下:D – SomethingOn

+0

除非我做錯了什麼,hook_theme()函數正在創建一個完全樣式的頁面,該頁面被注入DOM而不是我的custom.tpl.php文件。有沒有辦法運行一個tpl.php文件沒有它主題和整個頁面? – SomethingOn

+0

本頁的答案引導我到正確的答案:D http://stackoverflow.com/questions/3886898/how-do-i-decide-between-themenode-node-and-drupal-rendernode-content-f – SomethingOn

相關問題