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

I am trying to bring thematic content to a page, and I was trying to read the theme () function and how it works. As I understand it, it provides a method for generating thematic HTML. This is exactly what I want. Now I don’t understand how to pass it HTML or variables that I want HTML to be generated. What is the $ hook parameter? Is this a .tpl.php file? How to structure this file so that HTML is displayed in the page content section? Can someone explain the theme () function in a very simple way?

Thanks,

+4
source share
1 answer

You must write your own module. In your module, you must define your theme using the 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 the file your_template_filename.tpl.php in the folder of your module, and in this file you will have the variables $nid and $title (in this example). Your template file will look like this:

 // 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 of your site. Should be called like this:

 $variables = array( 'nid' => $nid, 'title' => $title ); $output = theme('your_theme_key', $variables); print $output; 
+11
source

Source: https://habr.com/ru/post/1382905/


All Articles