You are here

drupal主题 初始化默认值

g089h515r806 的头像
Submitted by g089h515r806 on 星期日, 2008-08-31 09:09

初始化默认值

        由于我们不能保证用户是否会访问页面admin/build/themes/settings/themeName,所以我们需要为我们的自定义设置初始化默认值。

只有当我们提交过admin/build/themes/settings/themeName后,主题设置变量才被保存起来,所以在我们的template.php文件中,我们需要检查变量的设置情况。如果没被设置,我们需要将其设置为默认值。我们是这样做的,首先取出一个变量,查看它是不是为null,如果是的话,我们使用variable_set()来保存默认值,接着使用theme_get_setting('', TRUE)在Drupal内部强制刷新设置。

 

在你的template.php文件的顶部附近添加下面的代码:

<?php
/*
* Initialize theme settings
*/
if (is_null(theme_get_setting('garland_happy'))) {  // <-- change this line
  global $theme_key;

  /*
   * The default values for the theme variables. Make sure $defaults exactly
   * matches the $defaults in the theme-settings.php file.
   */
  $defaults = array(             // <-- change this array
    'garland_happy' => 1,
    'garland_shoes' => 0,
  );

  // Get default theme settings.
  $settings = theme_get_settings($theme_key);
  // Don't save the toggle_node_info_ variables.
  if (module_exists('node')) {
    foreach (node_get_types() as $type => $name) {
      unset($settings['toggle_node_info_' . $type]);
    }
  }
  // Save default theme settings.
  variable_set(
    str_replace('/', '_', 'theme_'. $theme_key .'_settings'),
    array_merge($defaults, $settings)
  );
  // Force refresh of Drupal internals.
  theme_get_setting('', TRUE);
}
?>

注意,在前面代码中第一行的变量“garland_happy”,应被替换为你自定义主题设置中的变量名,而$defaults数据也应该是从你的theme-settings.php文件中拷贝过来的。

 

为新版本主题添加额外的设置

当你的主题发布了1.0版本以后,对于2.0版本,你将想要添加一些额外的自定义设置。这一过程非常直接。这里你需要注意的是第3步中的代码初始化。

 

  1. 在你的theme-settings.php文件中,向变量$defaults 和$form添加新的设置。
  2. 在你的template.php文件中,在初始化主题设置代码中,向变量$defaults中添加设置。
  3. 在你的template.php文件中,修改初始化代码,从你新添设置中任选一个,查看它是否存在。例如,如果你添加了多个设置,包括一个garland_slippers设置,你应该将初始化主题设置代码的第一行改为:
    if (is_null(theme_get_setting('garland_slippers'))) {
  4.  
  5.        这样就能将新加的自定义设置的默认值,添加到已保存的自定义设置的值中了。

原文:http://drupal.org/node/177868

译者:葛红儒, Think in Drupal

 

 

Drupal版本: