Upload
pakman-lh
View
1.395
Download
3
Embed Size (px)
DESCRIPTION
Presentación de la DrupalCamp Spain 2013 en Cáceres sobre las mejoras en la capa de Theme de Drupal 8 respecto Drupal 7
Citation preview
Twig y otros «themas» en Drupal 8: quiénes somos, de dónde venimos...
Quienes somosCristina [email protected] @ymbra.com
Pako [email protected]@ymbra.com
We are Drupal dreamers!
DISCLAIMER
● No somos expertos D8● NO es una sesión de TWIG (solamente)● NADA está 100% cerrado● SÍ aprenderemos algo (o eso esperamos)
THEMERS ARE WELLCOME
● Somos Drupaleros● Somos diseñadores● Somos themers● No somos desarrolladores● No somos sysadmins
Themers don't care about...
● Caching● OOP● PHP● MySQL, MongoDB● SOLID
Themers love...
● Marcado semántico● HTML5, SMACSS● SASS, compass, CSS3 ● Modernizr, JQueryUI● RWD● Ponys
Themers hate...
● DIVITIS● Acumulación de classes (estilos)● ...● Drupal ?¿
Themers hate...
● DIVITIS● Acumulación de classes (estilos)● ...● Drupal ?¿● WE ARE DRUPAL DREAMERS
Drupal 8 loves themers!!
● Configuración Archivo .yaml● CSS (Arquitectura, nomenclatura, etc)● Inspector de plantillas / variables
incorporado.● Mismas plantillas front y back● ...
Archivo de configuración
D8my_theme.infoD7 my_theme.info.yaml
name = Bartikdescription = A flexible, Recolorable ...package = Coreversion = VERSIONcore = 7.x
stylesheets[all][] = css/layout.cssstylesheets[all][] = css/style.cssregions[header] = Headerregions[help] = Helpregions[page_top] = Page topregions[page_bottom] = Page bottomregions[highlighted] = Highlighted...settings[shortcut_module_link] = 0
name: Bartiktype: themedescription: 'A flexible, recol...package: Coreversion: VERSIONcore: 8.xstylesheets: all: - css/layout.css print: - css/print.cssckeditor_stylesheets: - css/ckeditor-iframe.cssregions: header: Header help: Helpsettings: shortcut_module_link: '0'
Archivo de configuración
my_theme.infoD7
; Add a new CSS file:stylesheets[all][] = layout.css
; Override a CSS file:; WARNING: The file is moved from its original position to the; end of the CSS files stack! Use the PHP override code below.stylesheets[all][] = system.theme.css
; Remove a module CSS file by *adding* it but without supplying; the actual file in the filesystem:stylesheets[all][] = node.css
Archivo de configuración
D7
<?php/*** Implements hook_css_alter().*/function mytheme_css_alter(&$css) { // Override. if (isset($css['core/misc/vertical-tabs.css'])) { $css['core/misc/vertical-tabs.css']['data'] = drupal_get_path('theme', 'mytheme') . '/vertical-tabs.css';
// Remove.unset($css[drupal_get_path('module','system').'/system.theme.css']); }}?>
template.php
Archivo de configuración
D8
# Add a new CSS file:stylesheets: all: - layout.css
# Override a CSS file:stylesheets-override: - system.theme.css
# Remove a CSS file:stylesheets-remove: - node.css
mytheme.info.yml
http://dgo.to/1876600
Organización archivos CSS
Drupal 8 sigue la guía de estilo SMACSS para categorizar sus reglas CSS:
● Base — CSS reset.● Layout — estructura general, grid
systems.● Component — elementos UI reusables.● State — estilos que alteran los
elementos según la interacción.● Theme — estilos visuales (“look-and-
feel”) de los componentes.
Organización archivos CSS
Base● Uso de normalize.css
http://necolas.github.io/normalize.css/
● Y seguimiento de Boilerplate http://html5boilerplate.com/
Organización archivos CSS
Layout – Component - State● *.module.css ● *.admin.module.css● Borrar referencias a tags (li.first)● Sustituir # por .● Archivos -rtl.css. separados● Uso de selectores descriptivos● Reducir «supuestos»
Organización archivos CSS● Example Layout – Component - State:<div class="progress">
<label class="label">Installing Node Module</label>
<div class="progress__track">
<div class="progress__bar js-progress-percent" style="width: 63%"></div>
</div>
<div class="progress__description">
<div class="l-pull">Installed 15 of 24 modules</div>
<strong class="l-push">63%</strong>
</div>
<button class="progress__cancel" href="#" title="cancel">cancel</button>
</div>
Organización archivos CSS● Example Layout – Component - State:
/**
* Progress Bar component
*/
.progress {}
.progress__track {}
.progress__bar {}
.progress__description {}
.progress__cancel {}
.progress__cancel:focus,
.progress__cancel:hover {}
Organización archivos CSS● Example Layout – Component - State:<div class="progress progress--small">
<label class="label label--small">Uploading syndey-opera-house-sunset.jpg</label>
<div class="progress__track">
<div class="progress__bar" style="width: 29%"></div>
</div>
<div class="progress__description">
<div class="l-pull">Uploaded 221 of 762KB</div>
<strong class="l-push">29%</strong>
</div>
<a class="progress__cancel" href="#" title="cancel"><span class="visually-hidden">cancel</span></a>
</div>
Organización archivos CSS● Example Layout – Component - State:
/**
* Progress Bar small variant
*/
.progress--small .progress__track {}
.progress--small .progress__bar {}
.progress--small .progress__cancel {}
Inspección de plantillas
● Gracias a Twig tenemos un DEBUG de código:● Editando settings.php
$settings['twig_debug'] = TRUE;
<!-- THEME DEBUG --><!-- CALL: theme('node') --><!-- FILE NAME SUGGESTIONS: * node--article.html.twig * node--2.html.twig x node.html.twig--><!-- BEGIN OUTPUT from 'core/modules/node/templates/node.html.twig' -->...<!-- END OUTPUT from 'core/modules/node/templates/node.html.twig' -->
● Obteniendo automáticamente:
Inspección de variables
● Gracias a Twig tenemos un DEBUG de código:● Editando settings.php
● Podemos usar:
Obteniendo un resultado como krumo● BYE BYE DEVEL_THEMER module!
$settings['twig_debug'] = TRUE;
{{ dump(title) }}
Beneficios inherentes de TWIG
AL NO SER PHP:● Podemos usar las mismas plantillas desde el
BACK (PHP) como desde el FRONT (backbone, underscore, ...).
https://github.com/schmittjoh/twig.js● Las plantillas son interpretables (y editables)
desde los navegadores. ¿ Contemplate ?
Puntos flojos de Drupal 7
● Sintaxis● Inconsistencia● Complejidad● Redundancia● Seguridad
Puntos flojos de D7: Sintaxis
node.tpl.phpD7
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>> <?php print render($title_prefix); ?> <?php if (!$page): ?> <h2<?php print $title_attributes; ?>> <a href="<?php print $node_url; ?>"><?php print $title; ?></a> </h2> <?php endif; ?> <?php print render($title_suffix); ?>
<?php if ($display_submitted): ?> <div class="meta submitted"> <?php print $user_picture; ?> <?php print $submitted; ?> </div> <?php endif; ?> <div class="content clearfix"<?php print $content_attributes; ?>> <?php // We hide the comments and links now so that we can render them later. hide($content['comments']);
...
Puntos flojos de D7: Sintaxis
Puntos flojos de D7: Sintaxis
node.tpl.phpD7
<article id="node-{{ node.id }}" class="{{ attributes.class}} clearfix"{{ attributes }} role="article">
<header> {{ title_prefix }} {% if not page %} <h2{{ title_attributes }}> <a href="{{ node_url }}">{{ label }}</a> </h2> {% endif %} {{ title_suffix }}
{% if display_submitted %} <div class="meta submitted"> {{ user_picture }} {{ submitted }} </div> {% endif %} </header>...
Puntos flojos de D7: Sintaxis
Una única manera, mucho más fácil y reducida!● Mostrar variables: {{ title }}● Procesar: {% if not page %}● Comentar: {# That's just comment #}
Puntos flojos de D7: Inconsistencia
Si queremos modificar el marcado en Drupal 7 tenemos dos opciones:
● Mediante TPL● Mediante funciones theme()
Puntos flojos de D7: Inconsistencia
D7 node.tpl.php<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>> <?php print render($title_prefix); ?> <?php if (!$page): ?> <h2<?php print $title_attributes; ?>> <a href="<?php print $node_url; ?>"><?php print $title; ?></a> </h2> <?php endif; ?> <?php print render($title_suffix); ?>
<?php if ($display_submitted): ?> <div class="meta submitted"> <?php print $user_picture; ?> <?php print $submitted; ?> </div> <?php endif; ?> <div class="content clearfix"<?php print $content_attributes; ?>> <?php // We hide the comments and links now so that we can render them later. hide($content['comments']);
...
Puntos flojos de D7: Inconsistencia
node.pages.inc D7
función theme_node_preview()
Puntos flojos de D7: Inconsistencia
Si no sabemos PHP ...
Puntos flojos de D7: Inconsistencia
En Drupal 8 *solamente se usarán plantillas!
* A día de hoy se está trabajando en ello
Puntos flojos de D7: Inconsistencia
Render arrays VS theme functions
Puntos flojos de D7: Inconsistencia
En Drupal 8 *solamente se usarán render_arrays
* A día de hoy se está trabajando en ello
Puntos flojos de D7: Complejidad
Puntos flojos de D7: Complejidad
Puntos flojos de D7: Complejidad
x
xx
x xx
x
Puntos flojos de D7: Complejidad
En Drupal 8 se trata de reducir esta complejidad:– Pensando en casos de uso– Pensando en lo que el usuario (themer)
necesita.
– Meta Issue: http://dgo.to/2004872
Puntos flojos de D7: Complejidad
¿De qué manera?– 1: Build the theme registry– 2: Callback suggestions alter– 3: Prepare variables– 4: Alter variables– 5: Render output
– Meta Issue: http://dgo.to/2004872
Puntos flojos de D7: Redundancia
Cuando generamos varios TPL repetimos líneas de código:
● node--type.tpl.php● node--article.tpl.php● node--book.tpl.php● node--whatever.tpl.php● ...
Puntos flojos de D7: Redundancia
Twig permite extender una plantilla, heredando sus líneas y modificando solamente las diferencias.
Puntos flojos de D7: Redundancia
Ejemplo comment-wrapper.html.twig<section id="comments" class="{{ attributes.class }}"{{ attributes }}>
{% if comments %} {% codeblock title %} {{ title.prefix }} <h2 class="title">{{ 'Comments' | t }}</h2> {{ title.suffix }} {% endcodeblock %}
{{ comments }}
{% endif %}
{% if form %} <h2 class="title comment-form">{{ 'Add new comment' | t }}</h2> {{ form }} {% endif %}
</section>
Puntos flojos de D7: Redundancia
Ejemplo de otra plantilla
(comment-wrapper-forum.html.twig)
extendiendo la anterior.
{% extends "comment-wrapper.html.twig" %}
{% codeblock title %} {# code block here is empty to prevent title from showing on forums #}{% endcodeblock %}
Puntos flojos de D7: Redundancia
Existe un problema «parecido »con las funciones actuales de theme:
Puntos flojos de D7: Redundancia
Solución D8: Render arrays con herencia de sugerencias de templates.
Puntos flojos de D7: Seguridad
Posibilidad de usar PHP en las plantillas para:
<?php print $node->field_whatever['und'][0]['value']; ?>
● Imprimir cualquier tipo de valor...
<?php db_query(“DROP TABLE {node}”); ?>
● Realizar llamadas MySQL...
...
Puntos flojos de D7: Seguridad
Solución D8: usar Twig para tratar la información en la presentación y sanear previamente las variables para restringir los posibles datos a mostrar:
<h3>{{ node.field_whatever.0 }}</h3>
Mejoras en la API de D8
Nuevos theme hooks
hook hook hook hook hook
themetheme
suggestions
themesuggestions
alterprepare
preparealter
(preprocess)
drupalrender
defaulttemplate
templateoverride
themeregistry
themeregistry
alter
hook
* Todavía en progreso http://dgo.to/2004872
Nuevos theme hooks
hook hook hook hook hook
themetheme
suggestions
themesuggestions
alterprepare
preparealter
(preprocess)
drupalrender
defaulttemplate
templateoverride
themeregistry
themeregistry
alter
hook
NUEVO! hook_theme_suggestions()
* Todavía en progreso http://dgo.to/2004872
Nuevos theme hooks
hook hook hook hook hook
themetheme
suggestions
themesuggestions
alterprepare
preparealter
(preprocess)
drupalrender
defaulttemplate
templateoverride
themeregistry
themeregistry
alter
hook
NUEVO! hook_theme_suggestions_alter()
* Todavía en progreso http://dgo.to/2004872
● Antes:<?php/*** Implements hook_preprocess_HOOK() for node templates.*/function MYTHEME_preprocess_node($variables) { $variables['theme_hook_suggestion'] = 'node__' . 'my_suggestion';}?>
Nuevos theme hooks
NUEVO! hook_theme_suggestions_alter()
<?php/*** Implements hook_theme_suggestions_HOOK_alter().*/function MYTHEME_theme_suggestions_node_alter(array &$suggestions, array $variables) { $suggestions[] = 'node__' . 'my_suggestion';}?>
● Después:
Nuevos theme hooks
hook hook hook hook hook
themetheme
suggestions
themesuggestions
alterprepare
preparealter
(preprocess)
drupalrender
defaulttemplate
templateoverride
themeregistry
themeregistry
alter
hook
NUEVO! hook_prepare() o hook_theme_prepare_TEMPLATE_SUGGESTION()
* Todavía en progreso http://dgo.to/2004872
Nuevos theme hooks
hook hook hook hook hook
themetheme
suggestions
themesuggestions
alterprepare
preparealter
(preprocess)
drupalrender
defaulttemplate
templateoverride
themeregistry
themeregistry
alter
hook
Parecido a
hook_form_alter and hook_form_FORM_ID_alter● *Todavía en progreso
NUEVO! hook_prepare_alter() o hook_theme_prepare_TEMPLATE_SUGGESTION_alter()
En D8 todo es «renderizable»
● Todo es una Array hasta el final.● Se evita tener que bucear (regexp) en variables
de tipo string para alterar el marcado.● El marcado está en las plantillas SOLAMENTE
Traducción de cadenas en plantillas
● http://dgo.to/2047135● Implementación de t() y format_plural() con
contexto incluido:{% set count = comments|length %}{% trans %} {{ count }} comment was deleted successfully.{% plural count %} {{ count }} comments were deleted successfully.{% endtrans %}
{% trans with {'context': 'Long month name', 'langcode': 'fr'} %} January{% endtrans %}
«Theme Component Library»
● Crear un set «standard» de plantillas base para todos los elementos comunes.
● Ahora mismo es una lista de deseos
http://dgo.to/1804488
Conclusiones
● Con D8 los themers seremos felices (¡al fin!)
● ...● We need Drupal Heros!● http://dgo.to/1921610● http://dgo.to/1757550● Ask to @rteijeiro
¡Gracias!
¿Preguntas?Cristina [email protected] @ymbra.comPako [email protected]@ymbra.com