How to make Drupal return single HTML

Last modified
Sunday, February 12, 2017 - 07:31

Yesterday, I was working on a new requirement on a website I'm currently working on and the idea of it is make Drupal provide a Widget so anyone can copy/paste a single piece of HTML code inside a iframe and embedded that code anywhere, so providing ans iframe is not a big deal but of course the iframe will display inside it whatever comes from the source url you set for it, example:

<iframe frameborder="0" height="480" src="http://www.mysite.com/widget/"; target="_blank" align="center" width="360" scrolling="Auto"; bgcolor="#C9D3DE"> </iframe>

In this case "src" retrieves whatever content that url has, of course, this should be a single piece of html.
In order to do so with Drupal, you have to create a menu callback that will act as the provider of this piece of HTML code, something like this:

function my_module_menu(){
  $items['widget'] = array(
      'page callback' => 'my_widget',
      'access callback' => TRUE,
      'type' => MENU_CALLBACK,
  );
}

where $items['widget'] represents the path http://www.mysite.com/widget/, and "my_widget" is the callback function Drupal will call when this url is being accessed.
By concept this callback will return an entire Drupal page with whatever content we decide to include on this callback function, but wait, we don't need such thing, we don't want to embed a code that will represent a whole page instead of a block of HTML code only. In order to do so you can make this callback function print out the code you need instead of return it, example:

function my_module_widget(){
  $content = "<div>My HTML content</div>";
  //return $content //basic Drupal behavior
  print $content; //print out content
  exit; //don't let Drupal add the rest of the rendered html page
}

This function will return only the html code that represents the variable $content avoiding the inclusion of a whole Drupal themed page so the result you will see when embedding the iframe will be only: 

<div>My HTML content</div>

Topic

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.