A site I'm working on uses AJAX extensively to lazy load page data and to do Twitter style paging. I'd really like to be able to render the HTML via a template file as it will be easier to code and maintain than building an HTML string in a PHP function.
Is there some way to get the data from the DB and pass it to a theme function that loads a tpl file?
$node = node_load($nid);
$node_view = node_view($node);
echo drupal_render($node_view);
Yes, you can.
Drupal 7 AJAX requires a callback that needs to return the form element that has been updated and needs to be returned to the browser, or alternatively, a string containing HTML, or an array of custom Ajax commands.
One of the AJAX commands is ajax_command_html(), which you can use to insert the HTML returned from a theme function using a template.
You could have code similar to the following one:
The theme function is defined in
hook_theme()
as in the following code:To notice that the template filename must match the name of the theme function; you can use hyphens where the theme function name uses underscores, but you cannot have a theme function named "foo" that uses "bar" as name of the template file.
The name of the template file reported from
hook_theme()
doesn't include the extension (".tpl.php") that is added from Drupal when looking for the template file.