I have a custom theme we'll 开发者_如何学JAVAcall "MyTheme." In the template.php file, I have a function named "MyTheme_MyFunction."
In my page.tpl.php, should I be able to do this:
<?php print theme('MyFunction'); ?>
Or, do I have to do this:
<?php print MyTheme_Function(); ?>
I know the latter works, but shouldn't the former work too?
Use theme()
You should always call your theme functions via the theme()
function, as you show in your first example: theme('MyFunction')
. If you don't do this, you're crippling the Drupal theme system and not allowing other module developers to effectively override your output.
When writing your own theme functions, don't forget to use hook_theme
(explained here) to register your theme function with the theme registry. If you don't do this, calling theme('MyFunction')
won't work. Never hurts to clear caches after initially registering the function, either.
Example of why it's important
For example, in your theme's template.php, you can define your own theme_image
function to override how Drupal core handles images. You'd name your function name_of_theme_image
and get to work overriding what it returns. If theme_image
weren't always called as theme('image')
, you wouldn't be able to leverage this overriding behavior, because theme()
acts as the single point of entry and delegator of theme functions. The same is true of your theme functions.
The first definitely works, but for it to do so you need to tell Drupal about your theme function in hook_theme() (i.e. MyTheme_theme() in your theme's template.php) and then clear your theme cache.
See http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_theme/6 for more details.
You can make use of the preopreocess page hook
function themename_preprocess_page(&$variables) {
$variables['custom_name'] = function_name();
}
Then in the page.tpl.php you can use This is how the variables are passed to the tpl files.
Similarly for node.tpl.php you can use
function themename_preprocess_node(&$variables) {
}
精彩评论