Šablona template.php (en) umožňuje předefinovat výchozí a vytvářet vlastních funkce.
Odpovídající funkce je možné vyhledat na stránkce Default theme implementations (en).
Výraz "template" nahraďte za název tématu.
<?php
function template_preprocess_page(&$variables) {
//If front page remove title and breadcrumb
if (drupal_is_front_page()) {
$variables['breadcrumb'] = '';
$variables['title'] = '';
}
}
?>Téma vzheldu může nahradit CSS soubory definované jádrem a moduly přidáním stylopisu stejného jména a použitím funkce drupal_add_css(). Toto umožňuje tématům potlačit veškeré CSS soubory pokud je to nutné.
Například pokud chcete styl modules/system/system-menus.css definovaný jádrem nahradit (potlačit pro určitá média) vlastním:
<?php drupal_add_css(path_to_theme() .'/styles/system-menus.css', 'theme', 'screen, projection', TRUE); ?>
Výše uvedený příklad se načte pouze pro dané téma, tj. nenačte se pro případná podtémata. Pokud potřebujete používat přepis stylu i v podtématech přidejte jej přímo do .info souboru.
/** * Used to remove certain elements from the $head output within html.tpl.php * * @see http://api.drupal.org/api/drupal/modules--system--system.api.php/functio... * @param array $head_elements */ function YOUR_THEME_NAME_html_head_alter(&$head_elements) { $remove = array( 'system_meta_generator', 'metatag_canonical', 'metatag_shortlink' ); foreach ($remove as $key) { if (isset($head_elements[$key])) { unset($head_elements[$key]); } } // Use this loop to find out which keys are available. /* -- Delete this line to execute this loop echo '<pre>'; foreach ($head_elements as $key => $element) { echo $key ."\n"; } echo '</pre>'; // */ }
Pro přidání aktuální uživatelské role a cesty (verze A) do pole $body_classes stačí do souboru template.php v používaném tématu vzhledu vložit níže uvedený snippet a změňte MYTHEMENAME na aktuální název tématu vzhledu:
Verze A
/**
* Add current user's role and path to $body_classes shown in <body>
*/
function MYTHEMENAME_preprocess_html(&$vars) {
//$body_classes = array($vars['classes_array']); // normal theme
$body_classes = array($vars['attributes_array']['class']); // omega theme
if ($vars['user']) {
foreach($vars['user']->roles as $key => $role) {
$role_class = 'role-' . str_replace(' ', '-', $role);
//$vars['classes_array'][] = $role_class; // normal theme
$vars['attributes_array']['class'][] = $role_class; // omega theme
}
}
$path = drupal_get_path_alias($_GET['q']);
$aliases = explode('/', $path);
foreach($aliases as $alias) {
//$vars['classes_array'][] = drupal_clean_css_identifier($alias); // normal theme
$vars['attributes_array']['class'][] = drupal_clean_css_identifier($alias); // omega theme
}
}Verze B
/**
* Add current user's role to $body_classes shown in <body>
*/
function MYTHEMENAME_preprocess_page(&$vars) {
if ($vars['user']) {
foreach($vars['user']->roles as $key => $role){
$vars['class'][] = 'role-' . drupal_html_class($role);
}
}
}/**
* Add current user's role to $body_classes shown in <body>
*/
function MYTHEMENAME_preprocess_page(&$vars, $hook) {
$body_classes = array($vars['body_classes']);
if ($vars['user']) {
foreach($vars['user']->roles as $key => $role){
$role_class = 'role-' . str_replace(' ', '-', $role);
$body_classes[] = $role_class;
}
}
$vars['body_classes'] = implode(' ', $body_classes); // Concatenate with spaces
} Všechny funkce začínající slovem template_ nebo theme_ (např. theme_username) vytvářejí HTML výstup a je možné je upravit pomocí souboru template.php.
var_dump($variables);
kpr($variables);
Přesměrování uživatele na stránku Dashboard ihned po přihlášení:
/**
* Redirect user to a specific page after they login
*/
function MYTHEMENAME_user_login(&$edit, $account) {
$edit['redirect'] = 'admin/dashboard';
}/**
* Redirect user to a specific page after they login if they belong to a certain role
*/
function MYTHEMENAME_user_login(&$edit, $account) {
if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset' || variable_get('login_destination_immediate_redirect', FALSE)) {
if(in_array('administrator',$account->roles)) {
drupal_goto('admin/dashboard');
}
else {
drupal_goto('user/'.$account->uid);
}
}
}Přepis výstupu polí
function MYTHEMENAME_preprocess_field(&$variables, $hook) {
//kpr($variables);
// For field type "boolean"
if ($element['#field_type'] == 'list_boolean') {
// Add CSS class and change in Value
if ($variables['element']['#items'][0]['value'] == 1) {
$variables['classes_array'][] = 'true';
$variables['items'][0]['#markup'] = t('Yes');
}
else {
$variables['classes_array'][] = 'false';
$variables['items'][0]['#markup'] = t('No');
}
}
// For all field except specific type and name
if($variables['element']['#field_type'] !== 'text_with_summary' &&
$variables['element']['#field_type'] !== 'text_long' &&
$variables['element']['#field_name'] !== 'field_price' {
// For each item
foreach ($variables['items'] as $delta => $item) {
if (!empty($variables['items'][$delta]['#markup'])) {
// Add tag <strong>
$variables['items'][$delta]['#markup'] = '<strong>'. $variables['items'][$delta]['#markup'] .'</strong>';
}
}
}
}Náhrada nulové ceny za slovo zdarma ve výpisu Views:
/**
* Replace price 0 to free
*/
function MYTHEMENAME_preprocess_views_view_fields(&$variables) {
//kpr($variables);
if($variables['fields']['field_price']->content == 0) {
$variables['fields']['field_price']->content = t('free');
}
}Úprava řetězce "Submitted by [name] on [date]":
<?php
function MYTHEMENAME_preprocess_node(&$variables) {
$variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
// only username
//$variables['submitted'] = t('Submitted by !username', array('!username' => $variables['name']));
// only date
//$variables['submitted'] = t('Submitted on !datetime', array('!datetime' => $variables['date']));
// Drupal date formats (long, medium, short)
//$variables['date'] = format_date($variables['node']->created, 'short');
// Custom format types
//$variables['date'] = format_date($variables['node']->created, 'custom', 'F j, Y');
// Date Created -> Changed
//$variables['date'] = format_date($node->changed);
// Date Created -> Changed + custom username and date
/*$variables['date'] = format_date($node->changed);
if (variable_get('node_submitted_' . $node->type, TRUE)) {
$variables['display_submitted'] = TRUE;
$variables['submitted'] = t('Edited by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
$variables['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
} else {
$variables['display_submitted'] = FALSE;
$variables['submitted'] = '';
$variables['user_picture'] = '';
}*/
}
?>Úprava délky uživatelského jména:
/**
* Implements hook_preprocess_username().
*/
function MYTHEMENAME_preprocess_username(&$variables) {
$account = $variables['account'];
$variables['extra'] = '';
if (empty($account->uid)) {
$variables['uid'] = 0;
if (theme_get_setting('toggle_comment_user_verification')) {
$variables['extra'] = ' (' . t('not verified') . ')';
}
}
else {
$variables['uid'] = (int) $account->uid;
$user = user_load($account->uid);
if (isset($user->field_fullname['und'][0]['value'])) {
$name = $variables['name_raw'] = $user->field_fullname ['und'][0]['safe_value'];
}
else {
// Set the name to a formatted name that is safe for printing and
// that won't break tables by being too long. Keep an unshortened,
// unsanitized version, in case other preprocess functions want to implement
// their own shortening logic or add markup. If they do so, they must ensure
// that $variables['name'] is safe for printing.
$name = $variables['name_raw'] = format_username($account);
}
}
if (drupal_strlen($name) > 20) {
//$name = drupal_substr($name, 0, 15) . '...';
}
$variables['name'] = check_plain($name);
$variables['profile_access'] = user_access('access user profiles');
$variables['link_attributes'] = array();
// Populate link path and attributes if appropriate.
if ($variables['uid'] && $variables['profile_access']) {
// We are linking to a local user.
$variables['link_attributes'] = array('title' => t('View user profile.'));
$variables['link_path'] = 'user/' . $variables['uid'];
}
elseif (!empty($account->homepage)) {
// Like the 'class' attribute, the 'rel' attribute can hold a
// space-separated set of values, so initialize it as an array to make it
// easier for other preprocess functions to append to it.
$variables['link_attributes'] = array('rel' => array('nofollow'));
$variables['link_path'] = $account->homepage;
$variables['homepage'] = $account->homepage;
}
// We do not want the l() function to check_plain() a second time.
$variables['link_options']['html'] = TRUE;
// Set a default class.
$variables['attributes_array'] = array('class' => array('username'));
}function theme_username($object) {
if ($object->uid && $object->name) {
// Shorten the name when it is too long or it will break many tables.
if (drupal_strlen($object->name) > 20) {
$name = drupal_substr($object->name, 0, 15) .'...';
}
...např. na:
function MYTHEMENAME_username($object) {
if ($object->uid && $object->name) {
// Shorten the name when it is too long or it will break many tables.
if (drupal_strlen($object->name) > 30) {
$name = drupal_substr($object->name, 0, 25) .'...';
}
...
Místo phptemplate je z hlediska výkonu vhodnější psát název tématu. 
Pro přidání CSS atributů k menu odkazům použijte modul Menu Attributes.
Pokud potřebujete přidat třídy položkám LI použijte funkci theme_menu_link.
function YOURTHEME_menu_link__main_menu($variables){
} Pokud potřebujete přidat třídy seznamu UL použijte funkci theme_menu_tree.
Doplnění CSS do navigace:
/** * Overrides theme_menu_tree(). * Add bootstrap 'navbar-nav' class to Top Navigation menu */ function YOURTHEME_menu_tree__menu_top_navigation(&$variables) { return '<ul class="menu nav navbar-nav">' . $variables['tree'] . '</ul>'; }
Získání argumentů z URL:
$url = arg(); print_r($url); //print $url[0] .'|'. $url[1];
Získání query parametrů z URL:
$query = drupal_get_query_parameters(); //print_r $query; print $query['page'];
Doplnění počtu položek menu:
/**
* Process variables for menu-block-wrapper.tpl.php.
*
* @see menu-block-wrapper.tpl.php
*/
function THEMENAME_preprocess_menu_block_wrapper(&$variables) {
//$variables['classes_array'][] = 'menu-block-' . $variables['delta'];
$variables['classes_array'][] = 'menu-level-count-'. count(element_children($variables['content']));
}Připojení CSS pro Internet Explorer:
/**
* Generates IE CSS links for LTR and RTL languages.
*/
function phptemplate_get_ie_styles() {
global $language;
$iecss = "\n";
$iecss .= '<!--[if (lte IE 7)&(gte IE 5)]>'."\n ";
$iecss .= '<link type="text/css" rel="stylesheet" media="screen,
projection" href="'. base_path() . path_to_theme()
.'/styles/ie-7.css" />'."\n ";
if (defined('LANGUAGE_RTL') && $language->direction ==
LANGUAGE_RTL) {
$iecss .= '<link type="text/css" rel="stylesheet" media="screen,
projection" href="'. base_path() . path_to_theme()
.'/styles/ie-7-rtl.css" />'."\n ";
}
$iecss .= '<![if lt IE 7]>'."\n ";
$iecss .= '<link type="text/css" rel="stylesheet" media="screen,
projection" href="'. base_path() . path_to_theme()
.'/styles/ie-6.css" />'."\n ";
if (defined('LANGUAGE_RTL') && $language->direction ==
LANGUAGE_RTL) {
$iecss .= '<link type="text/css" rel="stylesheet" media="screen,
projection" href="'. base_path() . path_to_theme()
.'/styles/ie-6-rtl.css" />'."\n ";
}
$iecss .= '<![if lt IE 6]>'."\n ";
$iecss .= '<link type="text/css" rel="stylesheet" media="screen,
projection" href="'. base_path() . path_to_theme()
.'/styles/ie-5.5.css" />'."\n ";
if (defined('LANGUAGE_RTL') && $language->direction ==
LANGUAGE_RTL) {
$iecss .= '<link type="text/css" rel="stylesheet" media="screen,
projection" href="'. base_path() . path_to_theme()
.'/styles/ie-5.5-rtl.css" />'."\n ";
}
$iecss .= '<![if lt IE 5.5]>'."\n ";
$iecss .= '<link type="text/css" rel="stylesheet" media="screen,
projection" href="'. base_path() . path_to_theme()
.'/styles/ie-5.css" />'."\n ";
if (defined('LANGUAGE_RTL') && $language->direction ==
LANGUAGE_RTL) {
$iecss .= " ".'<link type="text/css" rel="stylesheet"
media="screen, projection" href="'. base_path() .
path_to_theme() .'/styles/ie-5-rtl.css" />'."\n ";
}
$iecss .= '<![endif]>'."\n ";
$iecss .= '<![endif]>'."\n ";
$iecss .= '<![endif]>'."\n";
$iecss .= '<![endif]-->'."\n";
return $iecss;
}
V používaném tématu vzhledu vytvořte (upravte) soubor template.php, do kterého vložte požadovanou funkci nalezenou přímo v Drupalu nebo na api.drupal.org:
/**
* Implements HOOK_form_alter()
*/
function MYTHEMENAME_form_alter(&$form, &$form_state, $form_id) {
//kpr($form); // require Devel modul
//dpm($form_id); // require Devel modul
//drupal_set_message($form_id); // print form ID to messages
//drupal_set_message(print_r($form, TRUE)); // print array to messages
//var_dump($form);
//echo $form_id .", ";
}/**
* Implements HOOK_form_FORM_ID_alter()
*/
function MYTHEMENAME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
//kpr($form); // require Devel modul
//var_dump($form);
//kpr(); // require Devel modul
}Např. modifikace atributů a textu tlačítek:
/**
* Implements HOOK_form_alter()
*/
function MYMODUELNAME_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'user_register') {
// change submit button
$form['submit']['#value'] = t('Complete the registration');
}
}/**
* Implements HOOK_form_alter()
*/
function MYTHEMENAME_form_alter(&$form, &$form_state, $form_id) {
//var_dump($form);
// submit input
if(isset($form['product_id']) && $form_id == 'commerce_cart_add_to_cart_form_' . $form['product_id']['#value']) {
$form['submit']['#attributes']['title'] = t('Add to Wishlist');
}
// 1. step of checkout
if($form_id == 'views_form_commerce_cart_form_default') {
$form['actions']['continue_shopping']['#value'] = t('Continue');
$form['actions']['submit']['#value'] = t('Update demand');
$form['actions']['checkout']['#value'] = t('Send demand');
}
// 2. step of checkout
if($form_id == 'commerce_checkout_form_checkout') {
$form['buttons']['continue']['#value'] = t('Send demand');
}
}Příklad úpravy exposed filtru (#process):
/**
* Custom process function
**/
function MYFUNCTION_process($element, $form_state, $form) {
//print('<pre>'.print_r($form,1).'</pre>');
//kpr($element);
//kpr($form_state);
// First element "CUSTOM_TEXT"
$element['CUSTOM_TEXT'] = array(
'#markup' => "<div class='my-class'>CUSTOM TEXT</div>",
);
// Second element "MY_LINK"
$element['MY_LINK'] = array(
'#type' => 'link',
'#prefix' => '<div class="MYCLASS">',
'#title' => '<span>'. t('TITLE') .'</span>',
'#suffix' => '</div>',
'#href' => 'MYURL',
'#id' => 'prev',
'#ajax' => array(
'wrapper' => 'level-form',
'method' => 'html',
),
'#options' => array(
'html' => true,
'fragment' => 'MY-ANCHOR',
'attributes' => array(
'title' => t('HOVER TITLE'),
),
'query' => array(
'year' => 2013,
'month' => 9,
)
),
'#weight' => -10,
);
return $element;
}function HOOK_form_alter(&$form, &$form_state, $form_id) {
$form['date']['value']['#process'][] = 'MYFUNCTION_process';
//kpr($form);
}...
Odstranění (úprava) popisu "celý den" u pole datum modulu Date:
/**
* Theme the way an 'all day' label will look.
*/
function phptemplate_date_all_day_label() {
return '';
}
Místo phptemplate je z hlediska výkonu vhodnější psát název tématu. 