Drupal 7 Themeing Notes

Hook Theme

Render Arrays

Note: The Form API (FAPI) makes use of render arrays.

Drupal 7 hook_theme() and Render array Example

<?php
/**
* Implements hook_theme()
* @return array
*/
function mymodule_theme(){
$items = array();

$items['mymodule_custom_template'] = array(
'path' => drupal_get_path('module', 'mymodule'),
'template' => 'mymodule_custom_template',
'variables' => array(
'account' => NULL,
'name' => '',
'mail' => '',
),
);
return $items;
}
/**
* Example usage within an arbitrary function
*/
function _mymodule_example_usage(){
global $user;

print theme( 'mymodule_custom_template', array(
'account' => $user,
'name' => format_username( $user ),
'mail' => $user->mail,
);
}
/**
* Implements hook_preprocess_HOOK()
* In this case HOOK is "mymodule_custom_template". The name of our custom template's key in the above array.
*/
function mymodule_preprocess_mymodule_custom_template( &$variables ){
// link the name to the user's page
$variables['name'] = l( $variables['name'], "user/{$account->uid}");
}
/**
* Implements hook_preprocess_HOOK()
*
* Render array examples attached to the main page content.
*
* @param $variables
*/
function mymodule_preprocess_page( &$variables )
{
// default render array #type is markup which accepts any HTML in
// the #markup property
$variables['page']['content']['my_render_array1'] = array(
'#markup' => '<p>Arbitrary HTML goes here</p>',
);
// example render array type 'html_tag'
$variables['page']['content']['my_render_array2'] = array(
'#type' => 'html_tag',
'#tag' => 'h2',
'#value' => 'Find Me',
);
// render array that uses a theme hook
// variables are passed to the function as #-prefixed properties
global $user;
$variables['page']['content']['my_render_array3'] = array(
'#theme' => 'mymodule_custom_template',
'#account' => $user,
'#name' => format_username( $user ),
'#mail' => $user->mail,
);
}
mymodule.module
<?php
/**
* Available variables
*
* $account object - drupal user account
* $name string - the account's formatted and linked name
* $mail string - the account's email address
*/
?><p><strong>Name: <?php print $name; ?></p>
<p><strong>Email: <?php print $mail; ?></p>
mymodule_custom_template.tpl.php
0 Thoughts

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *