60
Twig y otros «themas» en Drupal 8: quiénes somos, de dónde venimos...

Twig y otros "themas" en Drupal 8

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

Page 1: Twig y otros "themas" en Drupal 8

Twig y otros «themas» en Drupal 8: quiénes somos, de dónde venimos...

Page 2: Twig y otros "themas" en Drupal 8

Quienes somosCristina [email protected] @ymbra.com

Pako [email protected]@ymbra.com

We are Drupal dreamers!

Page 3: Twig y otros "themas" en Drupal 8

DISCLAIMER

● No somos expertos D8● NO es una sesión de TWIG (solamente)● NADA está 100% cerrado● SÍ aprenderemos algo (o eso esperamos)

Page 4: Twig y otros "themas" en Drupal 8

THEMERS ARE WELLCOME

● Somos Drupaleros● Somos diseñadores● Somos themers● No somos desarrolladores● No somos sysadmins

Page 5: Twig y otros "themas" en Drupal 8

Themers don't care about...

● Caching● OOP● PHP● MySQL, MongoDB● SOLID

Page 6: Twig y otros "themas" en Drupal 8

Themers love...

● Marcado semántico● HTML5, SMACSS● SASS, compass, CSS3 ● Modernizr, JQueryUI● RWD● Ponys

Page 7: Twig y otros "themas" en Drupal 8

Themers hate...

● DIVITIS● Acumulación de classes (estilos)● ...● Drupal ?¿

Page 8: Twig y otros "themas" en Drupal 8

Themers hate...

● DIVITIS● Acumulación de classes (estilos)● ...● Drupal ?¿● WE ARE DRUPAL DREAMERS

Page 9: Twig y otros "themas" en Drupal 8

Drupal 8 loves themers!!

● Configuración Archivo .yaml● CSS (Arquitectura, nomenclatura, etc)● Inspector de plantillas / variables

incorporado.● Mismas plantillas front y back● ...

Page 10: Twig y otros "themas" en Drupal 8

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'

Page 11: Twig y otros "themas" en Drupal 8

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

Page 12: Twig y otros "themas" en Drupal 8

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

Page 13: Twig y otros "themas" en Drupal 8

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

Page 14: Twig y otros "themas" en Drupal 8

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.

Page 15: Twig y otros "themas" en Drupal 8

Organización archivos CSS

Base● Uso de normalize.css

http://necolas.github.io/normalize.css/

● Y seguimiento de Boilerplate http://html5boilerplate.com/

Page 16: Twig y otros "themas" en Drupal 8

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»

Page 17: Twig y otros "themas" en Drupal 8

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>

Page 18: Twig y otros "themas" en Drupal 8

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 {}

Page 19: Twig y otros "themas" en Drupal 8

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>

Page 20: Twig y otros "themas" en Drupal 8

Organización archivos CSS● Example Layout – Component - State:

/**

* Progress Bar small variant

*/

.progress--small .progress__track {}

.progress--small .progress__bar {}

.progress--small .progress__cancel {}

Page 21: Twig y otros "themas" en Drupal 8

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:

Page 22: Twig y otros "themas" en Drupal 8

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) }}

Page 23: Twig y otros "themas" en Drupal 8

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 ?

Page 24: Twig y otros "themas" en Drupal 8

Puntos flojos de Drupal 7

● Sintaxis● Inconsistencia● Complejidad● Redundancia● Seguridad

Page 25: Twig y otros "themas" en Drupal 8

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']);

...

Page 26: Twig y otros "themas" en Drupal 8

Puntos flojos de D7: Sintaxis

Page 27: Twig y otros "themas" en Drupal 8

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>...

Page 28: Twig y otros "themas" en Drupal 8

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 #}

Page 29: Twig y otros "themas" en Drupal 8

Puntos flojos de D7: Inconsistencia

Si queremos modificar el marcado en Drupal 7 tenemos dos opciones:

● Mediante TPL● Mediante funciones theme()

Page 30: Twig y otros "themas" en Drupal 8

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']);

...

Page 31: Twig y otros "themas" en Drupal 8

Puntos flojos de D7: Inconsistencia

node.pages.inc D7

función theme_node_preview()

Page 32: Twig y otros "themas" en Drupal 8

Puntos flojos de D7: Inconsistencia

Si no sabemos PHP ...

Page 33: Twig y otros "themas" en Drupal 8

Puntos flojos de D7: Inconsistencia

En Drupal 8 *solamente se usarán plantillas!

* A día de hoy se está trabajando en ello

Page 34: Twig y otros "themas" en Drupal 8

Puntos flojos de D7: Inconsistencia

Render arrays VS theme functions

Page 35: Twig y otros "themas" en Drupal 8

Puntos flojos de D7: Inconsistencia

En Drupal 8 *solamente se usarán render_arrays

* A día de hoy se está trabajando en ello

Page 36: Twig y otros "themas" en Drupal 8

Puntos flojos de D7: Complejidad

Page 37: Twig y otros "themas" en Drupal 8

Puntos flojos de D7: Complejidad

Page 38: Twig y otros "themas" en Drupal 8

Puntos flojos de D7: Complejidad

x

xx

x xx

x

Page 39: Twig y otros "themas" en Drupal 8

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

Page 40: Twig y otros "themas" en Drupal 8

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

Page 41: Twig y otros "themas" en Drupal 8

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● ...

Page 42: Twig y otros "themas" en Drupal 8

Puntos flojos de D7: Redundancia

Twig permite extender una plantilla, heredando sus líneas y modificando solamente las diferencias.

Page 43: Twig y otros "themas" en Drupal 8

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>

Page 44: Twig y otros "themas" en Drupal 8

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 %}

Page 45: Twig y otros "themas" en Drupal 8

Puntos flojos de D7: Redundancia

Existe un problema «parecido »con las funciones actuales de theme:

Page 46: Twig y otros "themas" en Drupal 8

Puntos flojos de D7: Redundancia

Solución D8: Render arrays con herencia de sugerencias de templates.

Page 47: Twig y otros "themas" en Drupal 8

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...

...

Page 48: Twig y otros "themas" en Drupal 8

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>

Page 49: Twig y otros "themas" en Drupal 8

Mejoras en la API de D8

Page 50: Twig y otros "themas" en Drupal 8

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

Page 51: Twig y otros "themas" en Drupal 8

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

Page 52: Twig y otros "themas" en Drupal 8

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

Page 53: Twig y otros "themas" en Drupal 8

● 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:

Page 54: Twig y otros "themas" en Drupal 8

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

Page 55: Twig y otros "themas" en Drupal 8

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()

Page 56: Twig y otros "themas" en Drupal 8

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

Page 57: Twig y otros "themas" en Drupal 8

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 %}

Page 58: Twig y otros "themas" en Drupal 8

«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

Page 59: Twig y otros "themas" en Drupal 8

Conclusiones

● Con D8 los themers seremos felices (¡al fin!)

● ...● We need Drupal Heros!● http://dgo.to/1921610● http://dgo.to/1757550● Ask to @rteijeiro

Page 60: Twig y otros "themas" en Drupal 8

¡Gracias!

¿Preguntas?Cristina [email protected] @ymbra.comPako [email protected]@ymbra.com