Share
Embed
Transcript
88 slides
-
¿Twig? Twig es en motor de templates para PHP. Rápido,
flexible y seguro. http://twig.sensiolabs.org/images/twig-logo.png -
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 -
Simplificar la creación de la vista en un modelo MVC
y ser más amigable para los diseñadores. -
<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> -
<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> -
<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 -
{{ muestra algo }} {% hace_algo %} {#
este es un comentario #} Conciso -
Conciso <?php echo $variable ?> <?= $variable ?> <?php echo
htmlspeciachars($variable) ?> <?php echo strtolower($variable) ?> -
<?php echo $variable ?> <?= $variable ?> {{ variable }}
<?php echo htmlspeciachars($variable) ?> {{ variable|escape }} {{ variable|e }} <?php echo strtolower($variable) ?> {{ variable|lower }} Conciso -
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; ?> -
<?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 -
Sintaxis Output {{ variable }} {{ object.property }} {{ array.key
}} {{ array[”key”] }} -
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 -
Sintaxis Output {{ foo.bar }} 1) $foo[‘bar’] 2) $foo->bar 3)
$foo->bar() 4) $foo->getBar() 5) $foo->isBar() -
Sintaxis Tags {% block %}{% endblock %} {% for item
in items %}{% endfor %} {% if condicion %}{% endif %} {% include “template.html” %} -
Sintaxis • autoescape • block • do • embed •
extends • filter • flush • for • from • if • import • include • macro • sandbox • set • spaceless • use • verbatim Tags built-in -
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 -
Sintaxis Funciones {{ function(variable) }} {{ function(variable, true) }} {{
function(variable, “texto”) }} -
Sintaxis • attribute • block • constant • cycle •
date • dump • include • max • min • parent • random • range • source • template_from_string Funciones built-in -
Sintaxis Tests {% if variable is numero %} ... {%
endif %} {% if variable is numero(...) %} ... {% endif %} -
Sintaxis • constant • defined • divisibleby • empty •
even • iterable • null • odd • sameas Tests built-in -
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 %} © Copyright 2011 by <a href="http://example.com/">you</a>. {% endblock %} </div> </body> </html> -
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 %} © 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 %} -
Extensible • Puedo agregar funcionalidades simples • Funciones • Filtros
• Tests • Puedo crear mis propias extensiones -
Extensible • Puedo agregar funcionalidades simples • Funciones • Filtros
• Tests • Puedo crear mis propias extensiones • Puedo sobrecargar funcionalidades built-in -
Seguro {% autoescape true %} {{ var }} {{ var|raw
}} {# escape inhabilitado #} {{ var|escape }}{# escape simple #} {% endautoescape %} {{ include('page.html', sandboxed = true) }} -
Errores Variable "foo" does not exist in “MyProject/tpl1.html” at line
1 Hello {{ foo }} -
Twig proporciona una extensión en C que mejora la performance
de algunas de sus funciones internas. -
Instalación de la extensión C $ cd ext/twig $ phpize
$ ./configure $ make $ make install # php.ini extension=twig.so -
Twig vs. PHP for - foreach {% for number in
1..10 %} * {{ number }} {% endfor %} {% for item in items %} * {{ item.name }} {% endfor %} -
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 %} -
Twig vs. PHP if {% if condicion %} Si {%
elseif condicion2 %} Puede ser... {% else %} No {% endif %} -
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”] %} -
Twig vs. PHP function {% macro saludo(nombre, apellido) %} <div>Hola
{{ nombre }} {{ apellido }}</div> {% endmacro %} -
Twig vs. PHP function {% macro saludo(nombre, apellido) %} <div>Hola
{{ nombre }} {{ apellido }}</div> {% endmacro %} {% import "macros.html" as macros %} -
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 -
Bootstrap $loader = new Twig_Loader_Filesystem($dir); $twig = new Twig_Environment($loader,
$options); echo $twig->render('index.html.twig', [ 'name' => 'Ismael' ]); -
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 -
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 -
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 -
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 -
Bootstrap $twig = new Twig_Environment($loader, [ 'cache' => '/path/to/cache', 'debug'
=> true, 'strict_variables' => true, 'autoescape' => true, ]); Environment -
$twig = new Twig_Environment($loader, $options); $filtro = new Twig_SimpleFilter('lower',
function ($string) { return strtolower($string); }); $twig->addFilter($filtro); Extendiendo Twig Filtros -
$twig = new Twig_Environment($loader, $options); $function = new Twig_SimpleFunction('function',
function () { // ... }); $twig->addFunction($function); Extendiendo Twig Funciones -
$twig = new Twig_Environment($loader, $options); $test = new Twig_SimpleTest('numero',
function ($number) { return is_numeric($number); }); $twig->addTest($function); Extendiendo Twig Tests -
Extendiendo Twig Extensiones Clases PHP o paquetes que agregan funcionalidades
al motor de templates. -
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 -
class Mi_Extension extends Twig_Extension { function getFilters() { }
function getTests() { } function getFunctions() { } function getGlobals() { } function getName() { } } Extendiendo Twig -
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 -
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 -
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 -
class Mi_Extension extends Twig_Extension { public function getGlobals() { return
[ "nombre" => "Ismael", "apellido" => "Ambrosi" ]; } } Extendiendo Twig Globals