drupal - 是否可以使用模板文件为 AJAX 调用返回 HTML?

标签 drupal drupal-7 drupal-theming drupal-ajax

我正在开发的一个网站广泛使用 AJAX 来延迟加载页面数据并进行 Twitter 风格的分页。我真的很希望能够通过模板文件呈现 HTML,因为它比在 PHP 函数中构建 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);

最佳答案

是的,可以。

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/

相关文章:

javascript - jquery 脚本检测 url 中的参数并调用带有类的链接

configuration - 如何在 Drupal 7 中使用 Mandrill 发送群发邮件

drupal - 如何在drupal中获取站点/所有文件夹的绝对路径?

drupal - 将现有显示模板分配给 Drupal View

drupal - 将 HTML 模板转换为 Drupal 7

PHP - 克隆一个包含对自身的引用的对象?

css - views_slideshow控件修改Drupal 7

Drupal:如何在 hook_field_widget_form 中使用字段集

php - 在 Drupal 网站上使用 Cloudflare 重定向循环

drupal - 我想在 Drupal 7 中的单个自定义页面中放置 2 个表单