D8 Theming Themes - pierregermain/MyDrupal GitHub Wiki
- Consejos
- Estructura de un Theme
- Creación de un subtema a partir de Bartik
- Añadir Js / Css al Theme
- Templates
- Depuración
- Sugerencias de plantillas personalizadas
- Twig
- Preprocesses
- Formularios de configuración de Themes
Consejos
Conviene al trabajar en local con themes
- Habilitar "Reconstruir el registro de temas con cada carga de página".
- desactivar la opción "Combinar archivos CSS".
Estructura de un Theme
- *.info.yml. Es obligatorio. Valores posibles
- Contiene las regiones del tema. Se deberían usar los mismos nombres que las que se usan en bartik por compatibilidad
- *.libraries.yml. Archivos css/js que usa el theme
- *.breakpoints.yml. Definición de los breakpoints (diseño responsivo) del tema
- *.theme. Preprocceses
- *.logo.png
- *.screenshot.png
- css/
- js/
- templates
- Las regiones se usan en page.html.twig con el formato page.nombre_region
- config/
Creación de un subtema a partir de Bartik
*.info.yml
name: 'Bartik Forcontu'
type: theme
base theme: bartik
description: 'Subtema a partir de Bartik'
core: '8.x'
libraries:
- b_forcontu/global-styling
*.libraries.yml
global-styling:
css:
theme:
css/style.css: {}
css/style.css
#header {
background-color: #C7D0D6;
background-image: none;
}
Añadir Js / Css al Theme
- Link oficial
- Normalmente se añaden desde la librería *.libraries.yml. Si hay dependencias a alguna librería externa se debe indicar
- Normalmente se crea una librería llamada global-styling que contiene todos los css del tema.
- los archivos CSS se cargarán en el orden especificado.
foo:
version: 1.x
css:
theme:
css/foo.css: {}
js:
js/foo.js: {}
dependencies:
- core/jquery
Templates
Orden:
html ---> page ---> region
|
└---> block
|
└---> node ---> comment
html.html.twig
/core/modules/system/templates/html.html.twig
Variables:
- head_title
- logged_in
- node_type
- page (procesado desde page.html.twig)
page.html.twig
/core/modules/system/templates/page.html.twig
Variables:
- base_path
- is_front
- logged_in
- is_admin
- front_page
- $title
- messages
- node
- Regiones (page.header, etc.)
node.html.twig
/core/modules/node/templates/node.html.twig
El resultado de la plantilla se muestra en la plantilla de página (page.html.twig) dentro de la variable de región {{ page.content }}
Variables:
- node
- label
- content
- etc.
block.html.twig
/core/modules/block/templates/block.html.twig
Variables:
- plugin_id
- label
- etc.
region.html.twig
/core/modules/system/templates/region.html.twig.
Depuración
Sugerencias de plantillas personalizadas
Desde el archivo *.theme podemos crear nuestras propias plantillas pesonalizadas
[hook_theme_suggestions_alter(array &$suggestions, array $variables, $hook)](https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/func tion/hook_theme_suggestions_alter/8)
Como alternativa, si vamos a actuar sobre un HOOK específico, podemos utilizar la siguiente función:
[hook_theme_suggestions_HOOK_alter(array &$suggestions, array $variables)](https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/func tion/hook_theme_suggestions_HOOK_alter/8)
Ejemplo: Creación de node--logged-in.html.twig y node--type--logged-in.html.twig
/**
* Implements hook_theme_suggestions_HOOK_alter() for HOOK 'node'.
*/
function mymodule_theme_suggestions_node_alter(array &$suggestions,
array $variables) {
if (\Drupal::currentUser()->isAuthenticated()) {
$suggestions[] = 'node__' . 'logged_in';
$node = $variables['elements']['#node'];
if($node->getType()){
$suggestions[] = 'node__' . $node->getType() . '__logged_in';
}
}
}
OJO:
- El array $suggestions es pasado por referencia, así que podemos modificar o eliminar las sugerencias existentes.
- Los elementos en el array $suggestions están ordenados de menor a mayor especifidad.
Twig
Ver D8 Twig
Views Suggestions D9 Workaround
Views Suggestions
En Drupal 8 y 9 los views suggestions que salen al hacer debug no funcionan:
- https://www.drupal.org/project/drupal/issues/2839945
- https://www.drupal.org/project/drupal/issues/2923634
Pero, si se puede sobreescribir vistas usando suggestions aunque no funcionen. La sintaxis usada es la siguiente:
$suggestions[] = 'views_view__' . $view->id();
$suggestions[] = 'views_view__' . $view->current_display;
$suggestions[] = 'views_view__' . $view->id() . '__' . $view->current_display;
Eso significa que si queremos por ejemplo:
- crear un twig template para la view llamada "proyectos_educativos_primaria" usaríamos el siguiente twig:
- views-view--proyectos-educativos-primaria.html.twig
- crear un twig template para el bloque "block_1" de la view llamada "proyectos_educativos_primaria" usaríamos el siguiente twig:
- views-view--proyectos-educativos-primaria--block-1.html.twig
Preprocesses
Orden de ejecución de las funciones preprocess
- Preprocesses del núclero
- template_preprocess(&$variables, $hook)
- template_preprocess_HOOK(&$variables)
- Preprocesses de módulos
- MODULE_preprocess(&$variables, $hook)
- MODULE_preprocess_HOOK(&$variables)
- Preprocesses del motor del tema de drupal
- ENGINE_engine_preprocess(&$variables, $hook)
- ENGINE_engine_preprocess_HOOK(&$variables)
- Preprocesses del theming
- THEME_preprocess(&$variables, $hook)
- THEME_preprocess_HOOK(&$variables)
Preprocesses del theming
Nota: $variables se pasa por referencia
Ejemplo 1: Pasar variable globar twig_debug a todas las plantillas
/**
* Implements hook_preprocess().
*/
function mytheme_preprocess(&$variables, $hook) {
$variables['twig_debug'] = \Drupal::service('twig')->isDebug();
}
Ejemplo 2: Pasar una variable a una plantilla twig en concreto
- Nombre plantilla: comment.html.twig.
/**
* Implements hook_preprocess_HOOK() for comment.html.twig.
*/
function mytheme_preprocess_comment(&$variables) {
$variables['attributes']['class'][] = 'hello';
}
Formularios de configuración de Themes
Creación
- hook_form_system_theme_settings_alter()
- Se añade a .theme o .theme-settings.php
Alterar
- hook_form_system_theme_settings_alter(&$form, &$form_state)
Pasos para añadir una configuración
- Añadir la opción desde el hook
/**
* Implements hook_form_system_theme_settings_alter().
*/
function mytheme_form_system_theme_settings_alter(&$form,
\Drupal\Core\Form\FormStateInterface $form_state) {
$form['myoption'] = array(
'#type'
=> 'fieldset',
'#title'
=> t('Bartik Mytheme settings'),
);
$form['mytheme']['show_twig_message'] = array(
'#type' => 'checkbox',
'#title' => t('Display "Twig Debug" message'),
'#default_value' => theme_get_setting('show_twig_message'),
'#description' => t('Check this option if you want to display
a message when Twig Debug is enabled.'),
);
}
- Pasar la configuración desde un preprocess
$variables['show_twig_message'] = theme_get_setting('show_twig_message');
- Obtener la variable en nuestro twig
{{ show_twig_message }}
Valores por defecto en themes
- Fichero:
config/install/mytheme.settings.yml
Ejemplo:
features:
node_user_picture: 1
comment_user_picture: 1
comment_user_verification: 1
favicon: 1
logo:
use_default: 1
favicon:
use_default: 1
show_twig_message: 1
Para obtener un valor de configuración de theme
$theme_settings = theme_get_setting()
$mysetting = theme_get_setting('mysetting');