Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
TWIG            tips & tricksSUNSHINEPHP             JAVIER EGUILUZFEBRUARY 8TH 2013
Thanks to sponsors and organizers      Adam            Pablo      Culp            Godel
About me           Javier Eguiluz           I’m a programmer           and trainer from Spain.
ISYMFONY
I’m a long-term Symfony enthusiast
My Symfony2 book              Agile web development              with Symfony2
My Symfony website                          WINNER 2011                     Best Symfony Blog
I’m the « A week of Symfony» guy
I’m the « A week of Symfony» guy              this is me!
ITWIG
Twig is...• The best template engine for PHP.• Fast, secure and modern.• Easy to learn, to read and to write.• If you don’...
AGENDA
Agenda• Tips and tricks about Twig.• Advanced features.• Defensive template design.• Best practices.• New and noteworthy T...
NEW &NOTEWORTHY
Twig development activity is crazy!(last 12 months)      Twig             Jinja2                    (PHP, Symfony)   (Pyth...
New and noteworthy 1     2     3       4   5
«template_from_string» function{% set user_template = "{{ description[0:80] }}<br/> Price: {{ product.price }}" %}{% inclu...
New and noteworthy 1     2     3       4   5
«include» function{% include template.twig %}{{ include(template.twig) }}                             equivalent
«include» function              WRONG{% set content = include(index.twig) %}                                OK{% set conte...
«include» function                      WRONG{{ include(index.twig)|striptags(<a>)[0:80] }}{% set content %}              ...
New and noteworthy 1     2     3       4   5
«first» and «last» filters{% set firstElement = array|first %}{% set lastElement = array|last %}
«first» and «last» filters{% set first = array[0] %}{% set last = array[array|length - 1] %}
«first» and «last» filters{% set first = array[0] %}{% set last = array[array|length - 1] %}       only works for zero-   ...
«first» and «last» filters{{ [1, 2, 3, 4]|first }}                      1{{ { a: 1, b: 2, c: 3, d: 4 }|first }}        1{{...
New and noteworthy 1     2     3       4   5
Named arguments{{ text|convert_encoding(UTF-8, ISO-8859-1) }}{{ text|convert_encoding(        to=UTF-8, from=ISO-8859-1) }...
Named arguments{{ text|convert_encoding(UTF-8, ISO-8859-1) }}{{ text|convert_encoding(        to=UTF-8, from=ISO-8859-1) }...
Named arguments{{ text|convert_encoding(UTF-8, ISO-8859-1) }}{{ text|convert_encoding(        to=UTF-8, from=ISO-8859-1) }...
Named arguments{{ "now"|date("Y-m-d", "America/New_York") }}                      mandatory to set the                    ...
New and noteworthy 1     2     3       4   5
Functions and filters before 1.12$twig->addFunction(functionName,   new Twig_Function_Function(someFunction));$twig->addFu...
Functions and filters in Twig 1.12$twig->addFunction(new Twig_SimpleFunction(      twig_function, some_php_function));$twi...
Functions and filters in Twig 1.12$twig->addFunction(new Twig_SimpleFunction(      twig_function, some_php_function));$twi...
Functions and filters in Twig 1.12$twig->addFunction(new Twig_SimpleFunction(      twig_function, some_php_function));$twi...
OVERRIDING   FILTERS
USE WITHCAUTION
{% for i in array|sort %}  {# ... #}{% endfor %}
How is the                   array sorted?{% for i in array|sort %}  {# ... #}{% endfor %}
PHP defines 15 sorting functions•   asort()      •   array_multisort()•   arsort()     •   natcasesort()•   krsort()     •...
Overriding filters• Where can I find the PHP function used by Twig?• How can I override it with my own implementation?
Where Twig defines everythinglib/twig/Extension/Core.phpclass Twig_Extension_Core extends Twig_Extension {   public functi...
Where Twig defines everythinglib/twig/Extension/Core.phpclass Twig_Extension_Core extends Twig_Extension {   public functi...
«sort» filter uses «asort» functionnew Twig_SimpleFilter(sort, twig_sort_filter),// ...function twig_sort_filter($array){ ...
Overriding filters✔ Where can I find the PHP function•  used by Twig?• How can I override it with my own  implementation?
Replace «asort» with «natcasesort»// asortA1, a0, a10, a2// natcasesorta0, A1, a2, a10
1. Define a new Twig extensionclass MyCoreExtension      extends Twig_Extension_Core {   // ...}
2. Define the new «sort» filterclass MyCoreExtension extends Twig_Extension_Core {    public function getFilters() {      ...
2. Define the new «sort» filterclass MyCoreExtension extends Twig_Extension_Core {   public function getFilters() {       ...
2. Define the new «sort» filterclass MyCoreExtension extends Twig_Extension_Core{   public function getFilters()   {     r...
3. Register the new extension$twig = new Twig_Environment( ... );$twig->addExtension(   new MyCoreExtension());
This is now                   natcasesort{% for i in array|sort %}  {# ... #}{% endfor %}
DYNAMICFUNCTIONS
WordPress template tagsthe_ID()the_title()the_time()the_content()the_category()the_shortlink()
WordPress template tagsthe_ID()          class Post {                     $id = ...the_title()          $title = ...the_ti...
the_*()
Variable functions$twig->addFunction(     the_*,     new Twig_Function_Function(wordpress));function wordpress($property, ...
Variable functions$twig->addFunction(     the_*,     new Twig_Function_Function(wordpress));function wordpress($property, ...
Variable functions$twig->addFunction(  the_*,   new Twig_Function_Function(wordpress));          don’t use regexps,       ...
Variable functions in practice{{ the_ID() }}function wordpress(ID) { ... }{{ the_content() }}function wordpress(content) {...
Variable functions in practice{{ the_title(<h3>, </h3>) }}function wordpress(   title,   array(<h3>, </h3>)) { ... }
WordPress template tagsnext_image_link()next_post_link()next_posts_link()previous_image_link()previous_post_link()previous...
WordPress template tagsnext_image_link()        next_*_link()next_post_link()          next_*_link()next_posts_link()     ...
WordPress template tagsnext_image_link()       *_*_link()next_post_link()        *_*_link()next_posts_link()       *_*_lin...
USE WITHCAUTION
php_*()
php_* dynamic function      $twig->addFunction(new Twig_SimpleFunction(php_*,      function() {        $arg_list = func_ge...
Exposing PHP functions{{ php_print_r([value1, value2]) }}{{ php_crypt(mypassword) }}{{ php_memory_get_usage() }}{{ php_uni...
CUSTOM TAGS
{% source ‘...’ %}
{% source ‘...’ %}       file_get_contents()
The new «source» tag{% source home.twig %}{% source ../../../composer.json %}
How does Twig work internally{% sourcesimple.twig %}                      Twig                PHP     class               ...
How does Twig work internally{% sourcesimple.twig %}                      Twig                 PHP     class              ...
1. Create a new token parserclass SourceTokenParser extends Twig_TokenParser{   public function getTag()   {     return so...
2. Register the new token parser$loader = new Twig_Loader_Filesystem(...);$twig = new Twig_Environment($loader, array(...)...
3. Fill in the «parse» methodclass SourceTokenParser extends Twig_TokenParser{   public function parse(Twig_Token $token) ...
3. Fill in the «parse» methodclass SourceTokenParser extends Twig_TokenParser{   public function parse(Twig_Token $token) ...
4. Define the node class that compiles tagsclass SourceNode extends Twig_Node {    public function __construct(Twig_Node_E...
4. Define the node class that compiles tagsclass SourceNode extends Twig_Node {    public function __construct(Twig_Node_E...
The compiled PHP template// line 3echo file_get_contents("simple.twig");// ...                  {% source simple.twig %}//...
TEMPLATE LOADERS
Most apps use a single loader$loader = new Twig_Loader_Filesystem(   __DIR__./templates);$twig = new Twig_Environment($loa...
Chaining several loaders$loader1 = new Twig_Loader_Filesystem(...);$loader2 = new Twig_Loader_Filesystem(...);$loader = ne...
Chaining different loaders$loader1 = new Twig_Loader_Filesystem(...);$loader2 = new Twig_Loader_Array(...);$loader3 = new ...
Chaining different loaders$loader1 = new Twig_Loader_Filesystem(...);$loader2 = new Twig_Loader_Array(...);$loader3 = new ...
Adding loaders at runtime$loader = new Twig_Loader_Filesystem(/templates);$twig = new Twig_Environment($loader, array());i...
Storing templates in several folders$loader = new Twig_Loader_Filesystem(array(    __DIR__./default,    __DIR__./templates...
Storing templates in several folders$loader = new Twig_Loader_Filesystem(array(    __DIR__./default,    __DIR__./templates...
Adding folders at runtime$loader = new Twig_Loader_Filesystem(/templates);$path = $user_slug./templates;if (file_exists($p...
Prioritizing template folders$loader = new Twig_Loader_Filesystem(/templates);if(...) {   $loader->addPath($user_slug./tem...
Prioritizing template folders$loader = new Twig_Loader_Filesystem(/templates);if(...) {   $loader->addPath($user_slug./tem...
It’s difficult to prioritize folders$loader  ->addPath(...)  ->addPath(...)  ->prependPath(...)  ->addPath(...)  ->prepend...
NAMESPACES
Namespaces are better than folders       templates/         themes/index.twig         admin/index.twig         frontend/in...
Namespaces are better than folders$loader = new Twig_Loader_Filesystem(__DIR__./templates);$twig = new Twig_Environment($l...
App doesn’t work if folders change       templates/         themes/index.twig         frontend/index.twig       admin/
App doesn’t work if folders change        templates/           themes/index.twig    Whoops, looks like something went wron...
Registering and using namespaces$loader = new Twig_Loader_Filesystem(__DIR__./templates);$loader->addPath(__DIR__./admin, ...
Registering and using namespaces$loader = new Twig_Loader_Filesystem(__DIR__./templates);$loader->addPath(__DIR__./admin, ...
Registering and using namespaces$loader = new Twig_Loader_Filesystem(__DIR__./templates);$loader->addPath(__DIR__./admin, ...
Registering and using namespaces$loader = new Twig_Loader_Filesystem(__DIR__./templates);$loader->addPath(__DIR__./admin, ...
A practical use case$loader->addPath(   __DIR__./themes/default/admin, backend);// with namespaces$html = $twig->render(@b...
TWIG.JS
Twig.js = Twig inside JavaScript
Twig.js = Twig inside JavaScriptTWIG       TWIG
Twig.js = Twig inside JavaScriptTWIG       TWIGHTML                      HTML
Twig.js = Twig inside JavaScriptTWIG       TWIGHTML                      HTML          JSJS
Twig.js = Twig inside JavaScriptTWIG       TWIGHTML                      HTML          JSJS            TWIGTWIG
«A tale of two twig.js»         twig.js by         Johannes Schmitt         http://github.com/schmittjoh/twig.js         t...
«A tale of two twig.js»         twig.js by         Johannes Schmitt         http://github.com/schmittjoh/twig.js         t...
twig.js by Johannes Schmitt• A templating engine for Javascript  using Jinja/Twig style syntax.• It compiles your Twig tem...
Defining the template{# tweet.twig #}{% twig_js name="tweet" %}<p>  {{ message }} <span>by {{ author }}</span>  <time date...
Defining the template                              important!{# tweet.twig #}{% twig_js name="tweet" %}<p>  {{ message }} ...
Rendering the template in the browser<script type="text/javascript" src="twig.js"></script><script type="text/javascript" ...
Rendering the template in the browser<script type="text/javascript" src="twig.js"></script><script type="text/javascript" ...
«A tale of two twig.js»         twig.js by         Johannes Schmitt         http://github.com/schmittjoh/twig.js         t...
twig.js by John Roepke• A pure JavaScript implementation of  the Twig PHP templating language.• The goal is to provide a l...
Defining the template{# tweet.twig #}         not necessary{% twig_js name="tweet" %}<p>  {{ message }} <span>by {{ author...
Rendering the template in the browser<script type="text/javascript" src="twig.js"></script><script language="javascript" t...
Rendering the template in node.js<script type="text/javascript">var Twig = require("twig"), express = require(express), ap...
SANDBOX
A simple object$offer = new Offer();$offer->title = "Lorem Ipsum Dolor Sit Amet";$offer->description = "Ut enim ad minim v...
A simple object$offer = new Offer();$offer->title = "Lorem Ipsum Dolor Sit Amet";$offer->description = "Ut enim ad minim v...
Templates can show any propertyOffer data----------Title: {{ offer.title }}Description: {{ offer.description }}Commission:...
Twitter Sandbox• It’s a regular Twig extension.• Disabled by default.• It allows to restrict the functions,  filters, tags...
Define a new security policy$loader = new Twig_Loader_Filesystem(...);$twig = new Twig_Environment($loader, array());$prop...
Define a new security policy$loader = new Twig_Loader_Filesystem(...);                                                  co...
Define a new security policy$loader = new Twig_Loader_Filesystem(...);$twig = new Twig_Environment($loader, array());$prop...
Define a new security policy$loader = new Twig_Loader_Filesystem(...);$twig = new Twig_Environment($loader, array());$prop...
The template now displays an errorOffer data----------Title: {{ offer.title }}Description: {{ offer.description }}Commissi...
The template now displays an errorOffer data----------Title: {{ offer.title }}Description: {{ offer.description }}      Wh...
Security policy arguments$policy = new Twig_Sandbox_SecurityPolicy(     $tags,     $filters,     $methods,     $properties...
Allow to use just 3 filters$policy = new Twig_Sandbox_SecurityPolicy(     $tags,     array(escape, upper, lower),     $met...
Allow to use just 2 tags$policy = new Twig_Sandbox_SecurityPolicy(     array(include, extends),     $filters,     $methods...
Use any tag except include and extends$policy = new Twig_Sandbox_SecurityPolicy(   array_diff(      array_keys($twig->getT...
THE BASETEMPLATE
Adding a trace to all web pages<html><head> ... </head><body> ... <span data-host="Darwin 10.8.0 ..."       data-elapsed="...
Twig cache
cache/09/fc/2d8a188dda8245d295e6324582f2.php/* homepage.html.twig */class __TwigTemplate_09f8a...582f2      extends Twig_T...
cache/09/fc/2d8a188dda8245d295e6324582f2.php/* homepage.html.twig */class __TwigTemplate_09f8a...582f2      extends Twig_T...
The base template classclass __TwigTemplate_09f...2f2      extends Twig_Template{   // ...}
lib/Twig/Template.phpabstract class Twig_Template {     public function render(array $context)     {         // ...     } ...
lib/Twig/Template.phpabstract class Twig_Template {     public function render(array $context)     {                      ...
Use a different base template$loader = new Twig_Loader_Filesystem(...);$twig = new Twig_Environment($loader, array(    bas...
The new base template classclass MyTwigTemplate extends Twig_Template{    public function render(array $context)    {     ...
The new base template classabstract class MyTwigTemplate extends Twig_Template{  public function render(array $context)  {...
Adding a trace to all web pages<html><head> ... </head><body> ... <span data-host="Darwin 10.8.0 ..."       data-elapsed="...
DEFENSIVE   DESIGN
Errors will happen                 ERROR 500  ERROR
Errors will happen                     ERROR 500  ERROR          users prefer this
Default values{{ variable|default("value") }}(discount {{ discount|default(0) }}%)Hi {{ user_name|default("") }}!
The use_strict_variables option$loader = new Twig_Loader_Filesystem(...);$twig = new Twig_Environment($loader, array(     ...
The use_strict_variables option$loader = new Twig_Loader_Filesystem(...);$twig = new Twig_Environment($loader, array(     ...
Ignore missing templates{% include section_ ~ slug ~ .twig   ignore missing %}
Define fallback templates{% extends [  layout_ ~ locale ~ .html.twig,  layout.html.twig] %}
Use fallbacks and ignore errors{% include [  layout_ ~ locale ~ .html.twig,  layout.html.twig] ignore missing %}
Twig linter• A linter detects syntax errors  automatically.• Use it as a preventive measure to  detect errors before servi...
Twig linter in practice$twig = new Twig_Environment($loader, array(..));try {   $twig->parse($twig->tokenize($plantilla));...
INTEGRATING    TWITTER BOOTSTRAP
Twitter Bootstrap
Twitter Bootstrap grid model     3
Each row adds up to 12 columns     3         12 = 3 + 9
Each row adds up to 12 columns     3         12 = 3 + 4 + 5
Each row adds up to 12 columns     3   12 = 3 + 2 + 3 + 4
Most grids are based on 2 or 3 columns      3           2 columns
Most grids are based on 2 or 3 columns      3           2 columns
Most grids are based on 2 or 3 columns      3           3 columns
extends + include = embed
reuse a fixed  structureextends + include = embed
reuse a fixed   reuse  structure       contentsextends + include = embed
reuse a fixed    reuse  structure        contentsextends + include = embed              reuse contents and a              ...
Reusable 2-column grid{# grid_2.twig #}<div class="row">  <div class="{{ col1_span }} {{ col1_offset }}">     {% block col...
2-column grid in practice{% embed grid_2.twig with { col1_span: span9,                             col2_span: span3 } %}  ...
2-column grid in practice{% embed grid_2.twig with { col1_span:Magic                                    Twig   span9,     ...
2-column grid in practice{% embed grid_2.twig with { layout: 9_3 } %}  {% block column1 %} {# ... #} {% endblock %}  {% bl...
2-column grid in practice{% embed grid_2.twig with { layout: 9_3 } %}{% set col1_span = layout|split(_)[0:]|join %}{% set ...
3-column grid{% embed grid_3.twig with { layout: 3_6_3 } %}  {% block column1 %} {# ... #} {% endblock %}  {% block column...
3-column grid{% embed grid_3.twig with { layout: 3_6_3 } %}{% set col1_span = layout|split(_)[0:]|join %}{% set col2_span ...
Recap• New and noteworthy   • Sandbox• Overriding filters   • Base template• Dynamic functions    • Defensive design• Cust...
http://twig.sensiolabs.org
THANK YOU.
CONTACT ME
Contact me• javier.eguiluz@gmail.com• linkedin.com/in/javiereguiluz• twitter.com/javiereguiluz• github.com/javiereguiluz
Upcoming SlideShare
Loading in …5
×

WordPress template tagsnext_image_link()next_post_link()next_posts_link()previous_image_link()previous_post_link()previous_posts_link() Twig tips and tricks

162,281 views

Published on

WordPress template tagsnext_image_link()next_post_link()next_posts_link()previous_image_link()previous_post_link()previous_posts_link()

Published in: Technology
  • Are You Heartbroken? Don't be upset, let Justin help you get your Ex back. ◆◆◆ http://goo.gl/nkXEkK
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Download The Complete Lean Belly Breakthrough Program with Special Discount.  http://scamcb.com/bkfitness3/pdf
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD FULL BOOKS, INTO AVAILABLE FORMAT ......................................................................................................................... ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ......................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD FULL BOOKS, INTO AVAILABLE FORMAT ......................................................................................................................... ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ......................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Download The Complete Lean Belly Breakthrough Program with Special Discount. ♥♥♥ http://scamcb.com/bkfitness3/pdf
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

×