我正在开发的一个网站广泛使用 AJAX 来延迟加载页面数据并进行 Twitter 风格的分页。我真的很希望能够通过模板文件呈现 HTML,因为它比在 PHP 函数中构建 HTML 字符串更容易编码和维护。
是否有某种方法可以从数据库获取数据并将其传递给加载 tpl 文件的主题函数?
<小时/>$node = node_load($nid);
$node_view = node_view($node);
echo drupal_render($node_view);
最佳答案
是的,可以。
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”)。
关于drupal - 是否可以使用模板文件为 AJAX 调用返回 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8362844/