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

Templates con Twig - PHP Meetup Abril 2015

Templates con Twig - PHP Meetup Abril 2015

Charla de la meetup de PHP Montevideo el día 22 de Abril del 2015

Ismael Ambrosi

April 22, 2015
Tweet

More Decks by Ismael Ambrosi

Other Decks in Programming

Transcript

  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 • Creador por Fabien Potencier • Basado en Django

    • Soporte nativo en varios IDEs • Motor de templates por defecto en Symfony
  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. Bootstrap $loader = new Twig_Loader_Filesystem($dir);
 
 $twig = new Twig_Environment($loader,

    $options);
 
 echo $twig->render('index.html.twig', [
 'name' => 'Ismael'
 ]);
  8. 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
  9. 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
  10. 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
  11. 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
  12. Bootstrap $twig = new Twig_Environment($loader, [
 'cache' => '/path/to/cache',
 'debug'

    => true,
 'strict_variables' => true,
 'autoescape' => true,
 ]); Environment
  13. Conciso <?php echo $variable ?> <?= $variable ?> <?php echo

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

    <?php echo htmlspeciachars($variable) ?> {{ variable|escape }} {{ variable|e }} <?php echo strtolower($variable) ?> {{ variable|lower }} Conciso
  15. {{ muestra algo }}
 
 {% hace_algo %}
 
 {#

    este es un comentario #} Conciso
  16. $lexer = new Twig_Lexer($twig, array(
 'tag_comment' => array('{*', '*}'),
 'tag_block'

    => array('{', '}'),
 'tag_variable' => array('{$', '}'),
 ));
 
 $twig->setLexer($lexer); Conciso Tags de Smarty Puedo configurarlo para que use otros tags
  17. 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; ?> 
 
 
 

  18. <?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
  19. 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
  20. Sintaxis Output {{ foo.bar }} 1) $foo[‘bar’] 2) $foo->bar 3)

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

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

    extends • filter • flush • for • from • if • import • include • macro • sandbox • set • spaceless • use • verbatim Tags built-in
  23. 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
  24. Sintaxis • attribute • block • constant • cycle •

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

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

    even • iterable • null • odd • sameas Tests built-in
  27. 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>
  28. 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 %}
  29. Extensible • Puedo agregar funcionalidades simples • Funciones • Filtros

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

    • Tests • Puedo crear mis propias extensiones • Puedo sobrecargar funcionalidades built-in
  31. $twig = new Twig_Environment($loader, $options); 
 $filtro = new Twig_SimpleFilter('lower',

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

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

    function ($number) {
 return is_numeric($number);
 }); $twig->addTest($function); Extendiendo Twig Tests
  34. 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
  35. class Mi_Extension extends Twig_Extension
 {
 function getFilters() { }
 


    function getTests() { }
 
 function getFunctions() { }
 
 function getGlobals() { }
 
 function getName() { }
 } Extendiendo Twig
  36. 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
  37. 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
  38. 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
  39. class Mi_Extension extends Twig_Extension
 {
 public function getGlobals()
 {
 return

    [
 "nombre" => "Ismael",
 "apellido" => "Ambrosi"
 ];
 }
 } Extendiendo Twig Globals
  40. Seguro {% autoescape true %} {{ var }} {{ var|raw

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

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

    1..10 %} * {{ number }} {% endfor %} {% for item in items %} * {{ item.name }} {% endfor %}
  43. 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 %}
  44. Twig vs. PHP if {% if condicion %} Si {%

    elseif condicion2 %} Puede ser... {% else %} No {% endif %}
  45. 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”] %}
  46. Twig vs. PHP function {% macro saludo(nombre, apellido) %} <div>Hola

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

    {{ nombre }} {{ apellido }}</div> {% endmacro %} {% import "macros.html" as macros %}