Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

theme($hook, $variables = array()) and how it works in Drupal 7

Tags:

drupal

I'm trying to output themed content to a page and I've been trying to read up on the theme() function and how it works. As I understand, it provides a method to generate themed HTML. That's exactly what I want. Now, what I don't understand is how I pass it the HTML or the variables I want so that the HTML is generated. What's the $hook parameter? Is it a .tpl.php file? How do I structure this file so that the HTML is displayed in the content section of the page? Can someone explain the theme() function in a very simple way?

Thanks,

like image 900
KerrM Avatar asked Dec 21 '22 05:12

KerrM


1 Answers

You have to write your own module. In your module you have to define your theme using hook_theme function.

function mymodule_theme($existing, $type, $theme, $path) {
    return array(
        'your_theme_key' => array(
            'variables' => array(
                'nid' => NULL,
                'title' => NULL
            ),
            'template' => 'your_template_filename', // do not include .tpl.php
            'path' => 'path-to-your-template-file'
        )
    );
}

After that you should create file your_template_filename.tpl.php in your module's folder and in that file you would have variables $nid and $title (in this example). Your template file would be look like:

// define your html code using variables provided by theme
<div class="node node-type" id="node-<?php print $nid; ?>">
    <h3><?php print l($title, "node/{$nid}"); ?></h3>
</div>

After that you can use your theme in any modules in your site. Should be called like that:

$variables = array(
    'nid' => $nid,
    'title' => $title
);
$output = theme('your_theme_key', $variables);
print $output;
like image 70
Vlad Stratulat Avatar answered Dec 31 '22 14:12

Vlad Stratulat