3

What would be the cleanest way to route URLs to functions and return only the HTML output from those functions (a.k.a. the menu callback)?

If I use hook_menu() the string that's returned will be the HTML within the rest of the site. I want the page to display only the string returned from the menu callback.

Should I use drupal_set_header() in the same way drupal_json() does? Is this not inefficient having fully bootstrapped Drupal, and then changing the header at the last minute?

I want the fastest code path possible since this is going to be for widgets on external sites. I could start with a standalone .php file and bootstrap what I need but the hook_menu routing is nice.

How should you do this?

4

To show only the output of the callback, and not the complete page Drupal would render, output the HTML using print or echo; if you return the HTML output as string, Drupal will render the normal Drupal page, which includes the HTML your callback returns.

The code contained in index.php that causes this behavior is the following one:

// Menu status constants are integers; page content is a string.
if (is_int($return)) {
  switch ($return) {
    case MENU_NOT_FOUND:
      drupal_not_found();
      break;
    case MENU_ACCESS_DENIED:
      drupal_access_denied();
      break;
    case MENU_SITE_OFFLINE:
      drupal_site_offline();
      break;
  }
}
elseif (isset($return)) {
  // Print any value (including an empty string) except NULL or undefined:
  print theme('page', $return);
}

 

drupal_set_header() is used from drupal_json() to change the content type of the output (the "Content-Type" metadata); normally Drupal will set it to "text/html" which is not appropriate for what returned from a callback returning JSON; in that case, the content type that allows the requester to handle the output correctly is "text/javascript."

  • In D7 use drupal_add_http_header() instead of drupal_set_header() – sobi3ch Jul 27 '16 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.