Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Templates con Twig - Drupal Meetup Mayo 2016

Templates con Twig - Drupal Meetup Mayo 2016

Ismael Ambrosi

May 26, 2016

Transcript

88 slides
  1. ¿Twig? Twig es en motor de templates para PHP. Rápido,

    flexible y seguro. http://twig.sensiolabs.org/images/twig-logo.png
  2. Twig • Creado por Fabien Potencier • Basado en Django

    • Soporte nativo en varios IDEs • Soportado por Drupal 7 • Motor de templates por defecto en Drupal 8
  3. Simplificar la creación de la vista en un modelo MVC

    y ser más amigable para los diseñadores.
  4. <div class="content">
 <?php if ($condition1) { /* do something */

    } ?>
 
 <hr/>
 
 <?php if ($condition2) { /* do something else */ } ?>
 
 
 <h1>Posts</h1>
 
 
 <?php
 function getPosts()
 {
 // SELECT * FROM posts; (???)
 return $posts;
 }
 
 ?>
 
 
 <?php foreach (getPosts() as $post): ?>
 <h2><?php echo htmlspecialchars($post['date']); ?></h2> <p><?php echo htmlspecialchars($post[‘date'], ENT_QUOTES); ?></p>
 <?php endforeach; ?>
 
 </div>
  5. <div class="content">
 <?php if ($condition1) { /* do something */

    } ?>
 
 <hr/>
 
 <?php if ($condition2) { /* do something else */ } ?>
 
 
 <h1>Posts</h1>
 
 
 <?php
 function getPosts()
 {
 // SELECT * FROM posts; (???)
 return $posts;
 }
 
 ?>
 
 
 <?php foreach (getPosts() as $post): ?>
 <h2><?php echo htmlspecialchars($post['date']); ?></h2> <p> <?php echo htmlspecialchars(substr($post[‘date']), 100); ?> … </p>
 <?php endforeach; ?>
 
 </div>
  6. <html>
 <head>
 <title>{{ pageTitle|default('Mi super página web!') }}</title>
 </head>
 <body>


    <h1>{{ postTitle }}</h1>
 
 {% if userIsAdmin %}
 <a href="edit.php">Editar artículo</a>
 {% endif %}
 
 <div class="content">
 {{ postContent|e }}
 </div>
 </body>
 </html> Nuestra vista debería tener este estilo
  7. {{ muestra algo }}
 
 {% hace_algo %}
 
 {#

    este es un comentario #} Conciso
  8. Conciso <?php echo $variable ?> <?= $variable ?> <?php echo

    htmlspeciachars($variable) ?> <?php echo strtolower($variable) ?>
  9. <?php echo $variable ?> <?= $variable ?> {{ variable }}

    <?php echo htmlspeciachars($variable) ?> {{ variable|escape }} {{ variable|e }} <?php echo strtolower($variable) ?> {{ variable|lower }} Conciso
  10. Sintaxis <?php if (0 == count($items)): ?>
 <?php echo "No

    se han encontrado items."; ?>
 <?php else: ?>
 <?php foreach ($items as $item): ?>
 <?php echo "*".$item; ?>
 <?php endforeach; ?>
 <?php endif; ?> 
 
 
 

  11. <?php if (0 == count($items)): ?>
 <?php echo "No se

    han encontrado items."; ?>
 <?php else: ?>
 <?php foreach ($items as $item): ?>
 <?php echo "*".$item; ?>
 <?php endforeach; ?>
 <?php endif; ?> {% for item in items %}
 * {{ item.name }}
 {% else %}
 No se han encontrado items.
 {% endfor %} Sintaxis
  12. Sintaxis Output {{ foo.bar }} 1) Si es un array,

    el acceso es $foo[‘bar’] 2) Si no es un array, comprueba si es un objeto 1) Chequea existencia de propiedad “bar” en $foo 2) Chequea existencia de método “bar” en $foo 3) Chequea existencia de método “getBar” en $foo 4) Chequea existencia de método “isBar” en $foo
  13. Sintaxis Output {{ foo.bar }} 1) $foo[‘bar’] 2) $foo->bar 3)

    $foo->bar() 4) $foo->getBar() 5) $foo->isBar()
  14. Sintaxis Tags {% block %}{% endblock %} {% for item

    in items %}{% endfor %} {% if condicion %}{% endif %} {% include “template.html” %}
  15. Sintaxis • autoescape • block • do • embed •

    extends • filter • flush • for • from • if • import • include • macro • sandbox • set • spaceless • use • verbatim Tags built-in
  16. Sintaxis • abs • batch • capitalize • convert_encodi ng

    • date • date_modify • default • escape • first • format • join • json_encode • keys • last • length • lower • merge • nl2br • number_format • raw • replace • reverse • round • slice • sort • split • striptags • title • trim • upper • url_encode Filtros built-in
  17. Sintaxis • attribute • block • constant • cycle •

    date • dump • include • max • min • parent • random • range • source • template_from_string Funciones built-in
  18. Sintaxis Tests {% if variable is numero %} ... {%

    endif %} {% if variable is numero(...) %} ... {% endif %}
  19. Sintaxis • constant • defined • divisibleby • empty •

    even • iterable • null • odd • sameas Tests built-in
  20. Sintaxis Herencia <!DOCTYPE html> <html> <head> {% block head %}

    <link rel="stylesheet" href="style.css" /> <title>{% block title %}{% endblock %} - My Webpage</title> {% endblock %} </head> <body> <div id="content">{% block content %}{% endblock %}</div> <div id="footer"> {% block footer %} &copy; Copyright 2011 by <a href="http://example.com/">you</a>. {% endblock %} </div> </body> </html>
  21. Sintaxis Herencia <!DOCTYPE html> <html> <head> {% block head %}

    <link rel="stylesheet" href="style.css" /> <title>{% block title %}{% endblock %} - My Webpage</title> {% endblock %} </head> <body> <div id="content">{% block content %}{% endblock %}</div> <div id="footer"> {% block footer %} &copy; Copyright 2011 by <a href="http://example.com/">you</a>. {% endblock %} </div> </body> </html> {% extends "base.html" %} {% block title %}Index{% endblock %} {% block content %} <h1>Index</h1> <p class="important"> Welcome to my awesome homepage. </p> {% endblock %}
  22. Extensible • Puedo agregar funcionalidades simples • Funciones • Filtros

    • Tests • Puedo crear mis propias extensiones
  23. Extensible • Puedo agregar funcionalidades simples • Funciones • Filtros

    • Tests • Puedo crear mis propias extensiones • Puedo sobrecargar funcionalidades built-in
  24. Seguro {% autoescape true %} {{ var }} {{ var|raw

    }} {# escape inhabilitado #} {{ var|escape }}{# escape simple #} {% endautoescape %} {{ include('page.html', sandboxed = true) }}
  25. Instalación de la extensión C $ cd ext/twig $ phpize

    $ ./configure $ make $ make install # php.ini extension=twig.so
  26. Twig vs. PHP for - foreach {% for number in

    1..10 %} * {{ number }} {% endfor %} {% for item in items %} * {{ item.name }} {% endfor %}
  27. Twig vs. PHP for - foreach loop.index loop.first loop.length loop.revindex

    loop.last loop.parent {% for item in items %} {{ loop.index }} {{ item.name }} {% endfor %}
  28. Twig vs. PHP if {% if condicion %} Si {%

    elseif condicion2 %} Puede ser... {% else %} No {% endif %}
  29. Twig vs. PHP include - require {% include “template.html” %}

    {% include “template.html” with {“foo”: “bar”} %} {% include “template.html” only %} {% include “template.html” ignore missing %} {% include [“template.html”, “template2.html”] %}
  30. Twig vs. PHP function {% macro saludo(nombre, apellido) %} <div>Hola

    {{ nombre }} {{ apellido }}</div> {% endmacro %}
  31. Twig vs. PHP function {% macro saludo(nombre, apellido) %} <div>Hola

    {{ nombre }} {{ apellido }}</div> {% endmacro %} {% import "macros.html" as macros %}
  32. Cómo ya se mencionó, es el motor de template por

    defecto en Drupal 8 Así que olvídate de este paso si usas Drupal
  33. Bootstrap $loader = new Twig_Loader_Filesystem($dir);
 
 $twig = new Twig_Environment($loader,

    $options);
 
 echo $twig->render('index.html.twig', [
 'name' => 'Ismael'
 ]);
  34. Bootstrap // filesystem
 $loader = new Twig_Loader_Filesystem($dir);
 $loader = new

    Twig_Loader_Filesystem([
 '/path/to/templates',
 '/another/path/to/templates'
 ]);
 
 // string
 $loader = new Twig_Loader_String();
 
 $twig->render('Hello {{ name }}!', [
 'name' => 'Ismael'
 ]);
 
 // array
 $loader = new Twig_Loader_Array([
 'index.html.twig' => 'Hello {{ name }}!'
 ]); Loaders
  35. Bootstrap // filesystem
 $loader = new Twig_Loader_Filesystem($dir);
 $loader = new

    Twig_Loader_Filesystem([
 '/path/to/templates',
 '/another/path/to/templates'
 ]);
 
 // string
 $loader = new Twig_Loader_String();
 
 $twig->render('Hello {{ name }}!', [
 'name' => 'Ismael'
 ]);
 
 // array
 $loader = new Twig_Loader_Array([
 'index.html.twig' => 'Hello {{ name }}!'
 ]); Loaders
  36. Bootstrap // filesystem
 $loader = new Twig_Loader_Filesystem($dir);
 $loader = new

    Twig_Loader_Filesystem([
 '/path/to/templates',
 '/another/path/to/templates'
 ]);
 
 // string
 $loader = new Twig_Loader_String();
 
 $twig->render('Hello {{ name }}!', [
 'name' => 'Ismael'
 ]);
 
 // array
 $loader = new Twig_Loader_Array([
 'index.html.twig' => 'Hello {{ name }}!'
 ]); Loaders
  37. Bootstrap // filesystem
 $loader = new Twig_Loader_Filesystem($dir);
 $loader = new

    Twig_Loader_Filesystem([
 '/path/to/templates',
 '/another/path/to/templates'
 ]);
 
 // string
 $loader = new Twig_Loader_String();
 
 $twig->render('Hello {{ name }}!', [
 'name' => 'Ismael'
 ]);
 
 // array
 $loader = new Twig_Loader_Array([
 'index.html.twig' => 'Hello {{ name }}!'
 ]); Loaders
  38. Bootstrap $twig = new Twig_Environment($loader, [
 'cache' => '/path/to/cache',
 'debug'

    => true,
 'strict_variables' => true,
 'autoescape' => true,
 ]); Environment
  39. $twig = new Twig_Environment($loader, $options); 
 $filtro = new Twig_SimpleFilter('lower',

    function ($string) {
 return strtolower($string);
 }); $twig->addFilter($filtro); Extendiendo Twig Filtros
  40. $twig = new Twig_Environment($loader, $options); 
 $function = new Twig_SimpleFunction('function',

    function () {
 // ...
 }); $twig->addFunction($function); Extendiendo Twig Funciones
  41. $twig = new Twig_Environment($loader, $options); 
 $test = new Twig_SimpleTest('numero',

    function ($number) {
 return is_numeric($number);
 }); $twig->addTest($function); Extendiendo Twig Tests
  42. Extendiendo Twig Extensiones • Twig_Extension_Core: Agrega todas las funcionalidades principales

    de Twig • Twig_Extension_Escaper: Agrega funcionalidades de escape de salida • Twig_Extension_Sandbox: Habilita el modo sandbox • Twig_Extension_Optimizer: Optimiza el Árbol abstracto de sintaxis
  43. class Mi_Extension extends Twig_Extension
 {
 function getFilters() { }
 


    function getTests() { }
 
 function getFunctions() { }
 
 function getGlobals() { }
 
 function getName() { }
 } Extendiendo Twig
  44. class Mi_Extension extends Twig_Extension
 {
 public function getFilters()
 {
 return

    [
 new Twig_SimpleFilter("json", "json_encode"),
 "filtro" => new Twig_Filter_Method($this, "miFiltro")
 ];
 }
 
 public function miFiltro()
 {
 // ...
 }
 } Extendiendo Twig Filtros
  45. class Mi_Extension extends Twig_Extension
 {
 public function getTests()
 {
 return

    [
 "numero" => new Twig_Test_Method($this, "esNumero")
 ];
 }
 
 public function esNumero($valor)
 {
 return is_numeric($valor);
 }
 } Extendiendo Twig Tests
  46. class Mi_Extension extends Twig_Extension
 {
 public function getFunctions()
 {
 return

    [
 new Twig_SimpleFunction("dump", "var_dump"),
 "metodo" => new Twig_Function_Method($this, "miMetodo")
 ];
 }
 
 public function miMetodo()
 {
 // ...
 }
 } Extendiendo Twig Funciones
  47. class Mi_Extension extends Twig_Extension
 {
 public function getGlobals()
 {
 return

    [
 "nombre" => "Ismael",
 "apellido" => "Ambrosi"
 ];
 }
 } Extendiendo Twig Globals

More Decks by Ismael Ambrosi

Other Decks in Programming