Moh*_*kib 2 drupal drupal-themes
我正在构建一个能够上传自定义背景图像的主题,但现在我陷入了困境.
如何通过theme-setting.php以drupal格式正确添加FILE字段,之后如何在模板文件中获取此文件的公共URL?
ime*_*nox 12
在您的theme_form_system_theme_settings_alter挂钩中,您需要添加以下表单元素:
$form['theme_settings']['background_file'] = array(
'#type' => 'managed_file',
'#title' => t('Background'),
'#required' => FALSE,
'#upload_location' => file_default_scheme() . '://theme/backgrounds/',
'#default_value' => theme_get_setting('background_file'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
),
);
Run Code Online (Sandbox Code Playgroud)
这会将文件ID保存到你的主题settigns变量'background_file',注意我将上传位置设置为主题/背景,这将在你的文件夹中.
最后,您将使用file_create_url获取文件的完整URL:
$fid = theme_get_setting('background_file');
$image_url = file_create_url(file_load($fid)->uri);
Run Code Online (Sandbox Code Playgroud)
编辑:
在你的template.php中,你可以在theme_preprocess_page钩子中添加变量,这样所有tpl都可以访问它,这是如下:
function theme_preprocess_page(&$variables, $hook) {
$fid = theme_get_setting('background_file');
$variables['background_url'] = file_create_url(file_load($fid)->uri);
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!:d