5.3 自定义主题设置

自定义主题设置选项的方法是在主题文件夹下创建theme-setting.php文件,并添加以下代码:

<?php
 
function themename_form_system_theme_settings_alter(&$form, &$form_state) {
 
  $form['theme_settings']['your_option'] = array(
 
    '#type' => 'checkbox',
 
    '#title' => t('Your Option'),
 
    '#default_value' => theme_get_setting('your_option'),
 
  );
 
}

-['theme_settings'] 是用来为选项分组的,一般可以省略。但是如果不省略,你就能把自定义的主题选项和已有的默认选项遍在一个组中。

-[‘your_option'] 是新选项的名称

-#type 是表单类型

-#title  是选项标题/标签

-#default_value  默认值

在这里我们将 #default_value设置为 theme_get_setting(‘your_option’),这样Drupal会在数据库中查找并使用它,但是当它找不到的时候,drupal就会到.info文件中去寻找(注意,请深入理解drupal主题系统的这种行为,前辈们称其为“覆写”,外国人叫它“override”,当你理解之后,你会发现它几乎无处不在)。所以你还需要在.info文件中加入其默认值:

settings[your_option] = 1

最后你可以用theme_get_setting(‘your_option’);语句在你的tpl.php文件中来访问这个选项。

具体示例如下:当然你也可以在官网https://www.drupal.org/node/177868(link is external) 找到类似的例子。

在主题设置中添加一个副标题(sub-heading),用于在每个页面中显示出来:

我们知道,每个网站都有一个标题,假设某个网站除了原始标题之外,还需要一个副标题,并且允许管理员在网站后台进行设置,怎么实现?

 第一步,创建theme-setting.php文件并添加以下内容:

<?php
 
/**
 
 * Implements hook_form_FORM_ID_alter().
 
 */
 
function yourthemename_form_system_theme_settings_alter(&$form, &$form_state) {
 
//system_theme_settings是数据库中表的名称
 
//yourthemename是主题名称
 
  $form['yourthemename_subheading'] = array(
 
    '#type' => 'textfield',
 
    '#title' => t('Sub-heading'),
 
    '#default_value' => theme_get_setting('yourthemename_subheading'),
 
    '#description' => t('Displays a sub-heading below the main title. Different from the "slogan" because it will display on every page.'),
 
    '#weight' => -2,
 
  );
 
}

第二步:在.info文件中为它添加一个默认值,并清除缓存:

settings[yourthemename_subheading] = This is a default.

第三步:在page.tpl.php文件中引入对应的语句:

<?php if (theme_get_setting('yourthemename_subheading')): ?>
    <h2><?php print theme_get_setting('yourthemename_subheading'); ?></h2>
<?php endif; ?>

 

本书共55小节。


评论 (0)