Text Size
Wednesday, February 22, 2012
Get a look down
Drupal >> Passing variables to custom module template
Sunday, 08 January 2012 21:47

Passing variables to custom module template

Written by Nabil Sadki
Rate this item
(0 votes)

Among the best practices in developing a Drupal module, the use of templates is placed high on the list, this allows us to respect the MVC pattern (or at least a small part of it).

To do the job, supposing that you are using D6, so, you can insert some variables to your template like this :

1
2
3
4
5
6
7
8
9
10
<?php
// Your menu path is good
$items['mypath/mypage'] = array(
    'title' => 'My Page!',
    'page callback' => 'my_module_mypage',
    'page arguments' => array(1,2),
    'access callback' => true,
    'type' => MENU_CALLBACK,
);
?>

Second thing, we define the theme hook for our page

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
// We define here a new theme file for your your page
// Your theme file must be located in your module's folder
// you can use a subfolder to group all your module's theme files
// E.g : themes/my-module-theme.tpl.php
// Note that in theme files, we change _ by -
function my_module_theme() {
    return array(
        'my_module_theme' => array( // Keep that name in your mind
            'template' => 'my_module_theme',
                'arguments' => array(
                'my_var' => NULL,
                'my_var2' => NULL,
            ),
        )
    );
}
?>

 

Now we can create a file "my-module-theme.tpl.php" in the root folder of our module, and paste something like "foo AND bar!" Back to our my_module.module, the callback must be something like :

 

1
2
3
4
5
6
7
8
<?php
function my_module_mypage($x, $y) {
    // $x and $y are optionnal, so this is the first manner
    // to inject variables into your theme's file
    $output = theme("my_module_theme", $x, $y);
    return $output;
}
?>

 

Also you can use preprocess hook to insert variables

 

1
2
3
4
5
6
7
8
9
10
11
<?php
// The hook must be named like this : template_preprocess_NAME_OF_THEME_FILE
// where NAME_OF_THEME_FILE is the name that you kept in your mind ;)
function template_preprocess_my_module_theme(&$variables) {
    // Do some job
    $var1 = 'Foobar';
 
    // So in "my-module-theme.tpl.php", $my_var1 will print Foobar
    $variables['my_var1'] = $var1;
}
?>

 

That's all folks!

 

 

 

Last modified on Sunday, 08 January 2012 22:36
Nabil Sadki

Nabil Sadki

Hello, I am Nabyl, a Freelance web developer and a joomla addict. I have made many sites using the latter, but also patches for the core of this CMS. I like HipHop culture and world of warcraft. You can find find me on Twitter when i'm free...

Website: www.coins.ma E-mail: This e-mail address is being protected from spambots. You need JavaScript enabled to view it

Add comment



Usefull tricks