SlideShare a Scribd company logo
1 of 74
Download to read offline
Symfony Live 2011

being dangerous with Twig
a short story by Ryan Weaver

March 4th, 2011
being dangerous with Twig

     A 5-step guide to using Twig – the fast, secure and
           extensible PHP templating engine – to create clean
   template code, leverage powerful filters, make your designers
  write you love letters, write template functions that don't clog up your
global PHP namespace, take advantage of true template inheritance, hang out with
Django programmers and be able to talk template syntax, enjoy true and non- invasive
output escaping, have more time for your family, control whitespace, add global
    variables to all templates, stop lying when you try to tell yourself that <?php echo looks better than a
 simple {{, use the fancy for-else control, Rock some macros – little reusable code functions, do awesome stuff like “{% if i is divisibleby 2 %}”,
   mediate in the simplicity of your templates and drink more green tea, sandbox your template and whitelist capabilities – allowing Twig to be used in a CMS,
        take advantage of the fact that all templates compile to PHP classes that can extend a base class of your choosing, impress your friends by changing the print tag from
            {{ var }} to [all-your-base] var [are-belong-to-us], confuse the guy next to you by changing “is” and “is not” to mean the opposite things and convince him that he's misunderstood
                                             how logical expressions are used in programming languages all along, create a custom tag that takes the body of its block and tweets it,
                                                                                       write templates the expresses presentation and not program logic.




                                                                    Ryan Weaver
                                                                  Symfony Live 2011
@weaverryan


    » symfony

    » symfony documentation

    » collaboration

    » the lovely @leannapelham
iostudio: flying the symfony flag

  ●
      Advertising & Integrated Marketing Solutions

  • coming to you from
      » Nashville, TN
      » Washington, D.C.

  • 150 employees

  • and we're hiring!
act 1


        Why Twig?
because template
engines are awesome
Template engines

A template engine allows you to render a
presentation (HTML, XML, etc) via a template
in a controlled environment

It should allow special functionality that
makes creating templates easier (helpers,
template inheritance, etc)
a template engine
     is a tool
why not just render
 PHP templates?
PHP templating woes

» rendering template files is a hack: an include
  statement with output-buffering control

» no or faked template inheritance

» no isolation: PHP templates suck in any global
  variables or functions available
we need the brevity
   of templates

with the isolation of
  object-oriented
   programming
so give me some Twiggy pudding

 Twig is:                  Twig offers:
    » fast                    » true inheritance
    » flexible                » real output escaping
    » concise                 » tons of filters
    » secure                  » custom tags
    » fully-featured          » great documentation
    » Extensible              » global variables
    » designer-friendly       » the “for-else” control

             http://www.twig-project.org
Twig is concise

 and each template
compiles to an actual
     PHP object
seeing is believing
a moment of
templating zen
“The template system is meant to
express presentation, not program
             logic.”


             - Django documentation
Twig can easily be
 used anywhere
act 2


        Twig's simple life
Twig's three tags

Twig parses just three simple tags:

   » comment tag

   » print tag

   » block tag
a. do nothing (comment tags)

{# comment #}
   » totally ignored when rendered
b. say something (print tags)

{{ 'print me!' }}
   » prints the given expression
   » think “<?php echo”




   » If you're ultimately printing something, use
     this tag
c. do something (block tags)

{% set foo = 'inside a block tag' %}
  » used mostly for control-flow statements like if, for,
    include and block
  » can have beginning and end tags




   » if you're *doing* something and not *printing*
     something, use this tag
Twig's three tags


  » do nothing: {# comment tag #}

  » say something: {{ print tag }}

  » do something: {% block tag %}



   it's just that simple
act 3


        Everything is an
          expression
expressions: Twig guts

  » like PHP, most everything inside a tag
    is an expression




  » expressions are the most interesting and
    flexible part of Twig
Expressions   Block names
              Block-specific tokens
an expression can
 consist of many
 different things
strings, variables, arrays,
 functions, filters, tests,
       subscripts...
strings, numbers and variables
  » like any language, strings, numbers and
    variables are commonplace
arrays and hashes
  » arrays use [], hashes use {}
operators
  » twig has operators just like PHP, but extensible
    and with some extras
filters

   » a filter always follows a pipe (|) and modifies the
     value that precedes it
   » a filter may or may not take arguments
functions
  » just like PHP, returns a value based on some input
twig expresses himself


  » strings, numbers and variables

  » arrays and hashes

  » operators

  » filters

  » functions

   hey – it's simple like PHP, but flexible...
act 4


  twig on the battlefield
the test...


 » a template that displays a list of “widgets” in
   odd-even rows

 » render tags and other info about each widget

 » create basic, clean pagination
Resources/views/Main/widgets.html.twig
inside the SfLivePlayBundle
block tag




print tag
Let's clean things up
filter to title-case
   the widget name




filters to strip tags
and shorten the
widget's description
your presenter is lying to you...

   » the “truncate” filter isn't part of Twig, but
     is available via a repository of extensions

   » Everything in Twig is loaded via an Extension
     (even the core stuff)

   » Extensions are easy to use and create – we'll
     prove it later

   * https://github.com/fabpot/Twig-extensions
odd/even classes
   like a boss
 “really easily”
Twig function cycles through
the given array items




               Special variable available inside
               all “for” loops.
               The “loop” variable knows other
               tricks like “loop.last” and
               “loop.revindex”
flex some filters
apply the date filter




chain filters to turn a list of tags
into a comma-separated list
convenience,
 readability
even management
knows what this does
pagination?
function returns a positive
      radius of numbers around the
      center (e.g. 3, 4, 5, 6, 7)




the awesome loop variable tells us
when we're in the last iteration
the audacity: your speaker just lied again

 » but.... the “radius” function doesn't actually
   exist in Twig.




  but since it's pretty handy, let's create it!
act 5


        Twig extensions
Twig extensions
 everything in Twig is loaded by an “Extension” class:

   » filters
   » functions
   » operators
   » tests (e.g. divisbleby)
   » custom tags

  Extensions are EASY!
step 1: create a class that extends Twig_Extension
step 2: tell Twig about the extension
step 2: tell Twig about the extension (Symfony2)




* don't forget to import this file from your
  application's configuration (i.e. app/config/config.yml)
step 3: add some guts to the extension class
step 4: Celebrate!!!
* buy a round of drinks
* watch the sun set
* ask a cute stranger out to dinner
I want more!
 ok great – do some reading!

   » http://www.twig-project.org/doc/advanced.html
   » http://www.twig-project.org/doc/extensions.html


 seriously – the Twig docs are quite excellent
act 6


        after-dinner mint

             mmm
screw with the Twig syntax

   » because Twig is totally sandboxed (i.e. you
    control exactly what can and cannot be done
    inside a template, Twig is a perfect fit for a CMS.


   » and if Twig's syntax scares your clients... change it!
cool, what about
     debugging?

a debug tag ships with
 the twig-extensions
the “debug” extension is available for you
in Symfony2 - just enable it
prints every variable
              available




prints the foo variable
but we've only just
scratched the surface
there's much much more

   » inheritance                   name can be:
                                    * an item on an array
                                    * property on an object
   » macros (reusable code bits)    * getName()


   » subscripts



  or you can force it to
  *just* fetch “name”
  as an array item
Twig, he's a people-person

   » Twig loves contributions, so *get involved*!


   » https://github.com/fabpot/twig
   » https://github.com/fabpot/twig-extensions
   » http://groups.google.com/group/twig-users
The Symfony documentation wants you!

  » The Symfony2 documentation is a community effort


  » The best way as a beginner to get involved
   immediately!


  » Talk to me!!!
thank you


                        Ryan Weaver
                        iostudio
                        @weaverryan
                        www.thatsquality.com
                        ryan [at] thatsquality.com


        *do* reach out to me – i'd love to talk nerd with you

comments, feedback, questions


                        http://joind.in/2765

More Related Content

What's hot

Introduction to symfony2
Introduction to symfony2Introduction to symfony2
Introduction to symfony2Pablo Godel
 
Myphp-busters: symfony framework (php|tek 09)
Myphp-busters: symfony framework (php|tek 09)Myphp-busters: symfony framework (php|tek 09)
Myphp-busters: symfony framework (php|tek 09)Stefan Koopmanschap
 
A peek into Python's Metaclass and Bytecode from a Smalltalk User
A peek into Python's Metaclass and Bytecode from a Smalltalk UserA peek into Python's Metaclass and Bytecode from a Smalltalk User
A peek into Python's Metaclass and Bytecode from a Smalltalk UserKoan-Sin Tan
 
Introduction to Groovy Monkey
Introduction to Groovy MonkeyIntroduction to Groovy Monkey
Introduction to Groovy Monkeyjervin
 
Twig for Drupal 8 and PHP | Presented at OC Drupal
Twig for Drupal 8 and PHP | Presented at OC DrupalTwig for Drupal 8 and PHP | Presented at OC Drupal
Twig for Drupal 8 and PHP | Presented at OC Drupalwebbywe
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!olracoatalub
 
Spl in the wild - zendcon2012
Spl in the wild - zendcon2012Spl in the wild - zendcon2012
Spl in the wild - zendcon2012Elizabeth Smith
 
The why and how of moving to php 8
The why and how of moving to php 8The why and how of moving to php 8
The why and how of moving to php 8Wim Godden
 
Getting big without getting fat, in perl
Getting big without getting fat, in perlGetting big without getting fat, in perl
Getting big without getting fat, in perlDean Hamstead
 
The why and how of moving to php 7
The why and how of moving to php 7The why and how of moving to php 7
The why and how of moving to php 7Wim Godden
 
Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - BasicMosky Liu
 
Repoze Bfg - presented by Rok Garbas at the Python Barcelona Meetup October 2...
Repoze Bfg - presented by Rok Garbas at the Python Barcelona Meetup October 2...Repoze Bfg - presented by Rok Garbas at the Python Barcelona Meetup October 2...
Repoze Bfg - presented by Rok Garbas at the Python Barcelona Meetup October 2...maikroeder
 
Symfony Components
Symfony ComponentsSymfony Components
Symfony Componentsguest0de7c2
 
A Modest Introduction to Swift
A Modest Introduction to SwiftA Modest Introduction to Swift
A Modest Introduction to SwiftJohn Anderson
 
I pad uicatalog_lesson02
I pad uicatalog_lesson02I pad uicatalog_lesson02
I pad uicatalog_lesson02Rich Helton
 
From code to pattern, part one
From code to pattern, part oneFrom code to pattern, part one
From code to pattern, part oneBingfeng Zhao
 
Python Programming - I. Introduction
Python Programming - I. IntroductionPython Programming - I. Introduction
Python Programming - I. IntroductionRanel Padon
 
PHP Annotations: They exist! - JetBrains Webinar
 PHP Annotations: They exist! - JetBrains Webinar PHP Annotations: They exist! - JetBrains Webinar
PHP Annotations: They exist! - JetBrains WebinarRafael Dohms
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to GriffonJames Williams
 

What's hot (20)

Introduction to symfony2
Introduction to symfony2Introduction to symfony2
Introduction to symfony2
 
Myphp-busters: symfony framework (php|tek 09)
Myphp-busters: symfony framework (php|tek 09)Myphp-busters: symfony framework (php|tek 09)
Myphp-busters: symfony framework (php|tek 09)
 
A peek into Python's Metaclass and Bytecode from a Smalltalk User
A peek into Python's Metaclass and Bytecode from a Smalltalk UserA peek into Python's Metaclass and Bytecode from a Smalltalk User
A peek into Python's Metaclass and Bytecode from a Smalltalk User
 
Introduction to Groovy Monkey
Introduction to Groovy MonkeyIntroduction to Groovy Monkey
Introduction to Groovy Monkey
 
Twig for Drupal 8 and PHP | Presented at OC Drupal
Twig for Drupal 8 and PHP | Presented at OC DrupalTwig for Drupal 8 and PHP | Presented at OC Drupal
Twig for Drupal 8 and PHP | Presented at OC Drupal
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
 
Spl in the wild - zendcon2012
Spl in the wild - zendcon2012Spl in the wild - zendcon2012
Spl in the wild - zendcon2012
 
The why and how of moving to php 8
The why and how of moving to php 8The why and how of moving to php 8
The why and how of moving to php 8
 
Getting big without getting fat, in perl
Getting big without getting fat, in perlGetting big without getting fat, in perl
Getting big without getting fat, in perl
 
The why and how of moving to php 7
The why and how of moving to php 7The why and how of moving to php 7
The why and how of moving to php 7
 
Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - Basic
 
Repoze Bfg - presented by Rok Garbas at the Python Barcelona Meetup October 2...
Repoze Bfg - presented by Rok Garbas at the Python Barcelona Meetup October 2...Repoze Bfg - presented by Rok Garbas at the Python Barcelona Meetup October 2...
Repoze Bfg - presented by Rok Garbas at the Python Barcelona Meetup October 2...
 
Symfony Components
Symfony ComponentsSymfony Components
Symfony Components
 
A Modest Introduction to Swift
A Modest Introduction to SwiftA Modest Introduction to Swift
A Modest Introduction to Swift
 
I pad uicatalog_lesson02
I pad uicatalog_lesson02I pad uicatalog_lesson02
I pad uicatalog_lesson02
 
From code to pattern, part one
From code to pattern, part oneFrom code to pattern, part one
From code to pattern, part one
 
Python Programming - I. Introduction
Python Programming - I. IntroductionPython Programming - I. Introduction
Python Programming - I. Introduction
 
PHP Annotations: They exist! - JetBrains Webinar
 PHP Annotations: They exist! - JetBrains Webinar PHP Annotations: They exist! - JetBrains Webinar
PHP Annotations: They exist! - JetBrains Webinar
 
ClassJS
ClassJSClassJS
ClassJS
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to Griffon
 

Similar to Being Dangerous with Twig (Symfony Live Paris)

Twig internals - Maksym MoskvychevTwig internals maksym moskvychev
Twig internals - Maksym MoskvychevTwig internals   maksym moskvychevTwig internals - Maksym MoskvychevTwig internals   maksym moskvychev
Twig internals - Maksym MoskvychevTwig internals maksym moskvychevDrupalCampDN
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!Alessandro Giorgetti
 
Professional Help for PowerShell Modules
Professional Help for PowerShell ModulesProfessional Help for PowerShell Modules
Professional Help for PowerShell ModulesJune Blender
 
Python in the land of serverless
Python in the land of serverlessPython in the land of serverless
Python in the land of serverlessDavid Przybilla
 
Twig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHPTwig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHPFabien Potencier
 
Python introduction
Python introductionPython introduction
Python introductionRoger Xia
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
The Ring programming language version 1.5.4 book - Part 6 of 185
The Ring programming language version 1.5.4 book - Part 6 of 185The Ring programming language version 1.5.4 book - Part 6 of 185
The Ring programming language version 1.5.4 book - Part 6 of 185Mahmoud Samir Fayed
 
Getting Git Right
Getting Git RightGetting Git Right
Getting Git RightSven Peters
 
TapestryJfly
TapestryJflyTapestryJfly
TapestryJflykiuma
 
The Ring programming language version 1.5.3 book - Part 6 of 184
The Ring programming language version 1.5.3 book - Part 6 of 184The Ring programming language version 1.5.3 book - Part 6 of 184
The Ring programming language version 1.5.3 book - Part 6 of 184Mahmoud Samir Fayed
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
&lt;b>PHP&lt;/b> Reference: Beginner to Intermediate &lt;b>PHP5&lt;/b>
&lt;b>PHP&lt;/b> Reference: Beginner to Intermediate &lt;b>PHP5&lt;/b>&lt;b>PHP&lt;/b> Reference: Beginner to Intermediate &lt;b>PHP5&lt;/b>
&lt;b>PHP&lt;/b> Reference: Beginner to Intermediate &lt;b>PHP5&lt;/b>tutorialsruby
 
Instagram filters
Instagram filters Instagram filters
Instagram filters Thinkful
 
Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)Mohan Arumugam
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
Codemotion 2013 - Designing complex applications using html5 and knockoutjsCodemotion 2013 - Designing complex applications using html5 and knockoutjs
Codemotion 2013 - Designing complex applications using html5 and knockoutjsFabio Franzini
 
The Ring programming language version 1.5.1 book - Part 5 of 180
The Ring programming language version 1.5.1 book - Part 5 of 180The Ring programming language version 1.5.1 book - Part 5 of 180
The Ring programming language version 1.5.1 book - Part 5 of 180Mahmoud Samir Fayed
 
C++ Introduction brown bag
C++ Introduction brown bagC++ Introduction brown bag
C++ Introduction brown bagJacob Green
 

Similar to Being Dangerous with Twig (Symfony Live Paris) (20)

Twig internals - Maksym MoskvychevTwig internals maksym moskvychev
Twig internals - Maksym MoskvychevTwig internals   maksym moskvychevTwig internals - Maksym MoskvychevTwig internals   maksym moskvychev
Twig internals - Maksym MoskvychevTwig internals maksym moskvychev
 
Drupal 7 ci and testing
Drupal 7 ci and testingDrupal 7 ci and testing
Drupal 7 ci and testing
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!
 
Professional Help for PowerShell Modules
Professional Help for PowerShell ModulesProfessional Help for PowerShell Modules
Professional Help for PowerShell Modules
 
Python in the land of serverless
Python in the land of serverlessPython in the land of serverless
Python in the land of serverless
 
Twig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHPTwig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHP
 
Python introduction
Python introductionPython introduction
Python introduction
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
The Ring programming language version 1.5.4 book - Part 6 of 185
The Ring programming language version 1.5.4 book - Part 6 of 185The Ring programming language version 1.5.4 book - Part 6 of 185
The Ring programming language version 1.5.4 book - Part 6 of 185
 
Getting Git Right
Getting Git RightGetting Git Right
Getting Git Right
 
TapestryJfly
TapestryJflyTapestryJfly
TapestryJfly
 
The Ring programming language version 1.5.3 book - Part 6 of 184
The Ring programming language version 1.5.3 book - Part 6 of 184The Ring programming language version 1.5.3 book - Part 6 of 184
The Ring programming language version 1.5.3 book - Part 6 of 184
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;b>PHP&lt;/b> Reference: Beginner to Intermediate &lt;b>PHP5&lt;/b>
&lt;b>PHP&lt;/b> Reference: Beginner to Intermediate &lt;b>PHP5&lt;/b>&lt;b>PHP&lt;/b> Reference: Beginner to Intermediate &lt;b>PHP5&lt;/b>
&lt;b>PHP&lt;/b> Reference: Beginner to Intermediate &lt;b>PHP5&lt;/b>
 
Instagram filters
Instagram filters Instagram filters
Instagram filters
 
Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
Codemotion 2013 - Designing complex applications using html5 and knockoutjsCodemotion 2013 - Designing complex applications using html5 and knockoutjs
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
 
The Ring programming language version 1.5.1 book - Part 5 of 180
The Ring programming language version 1.5.1 book - Part 5 of 180The Ring programming language version 1.5.1 book - Part 5 of 180
The Ring programming language version 1.5.1 book - Part 5 of 180
 
C++ Introduction brown bag
C++ Introduction brown bagC++ Introduction brown bag
C++ Introduction brown bag
 

More from Ryan Weaver

Webpack Encore Symfony Live 2017 San Francisco
Webpack Encore Symfony Live 2017 San FranciscoWebpack Encore Symfony Live 2017 San Francisco
Webpack Encore Symfony Live 2017 San FranciscoRyan Weaver
 
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017Ryan Weaver
 
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...Ryan Weaver
 
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and moreSymfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and moreRyan Weaver
 
Symfony: Your Next Microframework (SymfonyCon 2015)
Symfony: Your Next Microframework (SymfonyCon 2015)Symfony: Your Next Microframework (SymfonyCon 2015)
Symfony: Your Next Microframework (SymfonyCon 2015)Ryan Weaver
 
Guard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful SecurityGuard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful SecurityRyan Weaver
 
Grand Rapids PHP Meetup: Behavioral Driven Development with Behat
Grand Rapids PHP Meetup: Behavioral Driven Development with BehatGrand Rapids PHP Meetup: Behavioral Driven Development with Behat
Grand Rapids PHP Meetup: Behavioral Driven Development with BehatRyan Weaver
 
Master the New Core of Drupal 8 Now: with Symfony and Silex
Master the New Core of Drupal 8 Now: with Symfony and SilexMaster the New Core of Drupal 8 Now: with Symfony and Silex
Master the New Core of Drupal 8 Now: with Symfony and SilexRyan Weaver
 
Silex: Microframework y camino fácil de aprender Symfony
Silex: Microframework y camino fácil de aprender SymfonySilex: Microframework y camino fácil de aprender Symfony
Silex: Microframework y camino fácil de aprender SymfonyRyan Weaver
 
Drupal 8: Huge wins, a Bigger Community, and why you (and I) will Love it
Drupal 8: Huge wins, a Bigger Community, and why you (and I) will Love itDrupal 8: Huge wins, a Bigger Community, and why you (and I) will Love it
Drupal 8: Huge wins, a Bigger Community, and why you (and I) will Love itRyan Weaver
 
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other ToolsCool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other ToolsRyan Weaver
 
The Wonderful World of Symfony Components
The Wonderful World of Symfony ComponentsThe Wonderful World of Symfony Components
The Wonderful World of Symfony ComponentsRyan Weaver
 
A PHP Christmas Miracle - 3 Frameworks, 1 app
A PHP Christmas Miracle - 3 Frameworks, 1 appA PHP Christmas Miracle - 3 Frameworks, 1 app
A PHP Christmas Miracle - 3 Frameworks, 1 appRyan Weaver
 
Doctrine2 In 10 Minutes
Doctrine2 In 10 MinutesDoctrine2 In 10 Minutes
Doctrine2 In 10 MinutesRyan Weaver
 
The Art of Doctrine Migrations
The Art of Doctrine MigrationsThe Art of Doctrine Migrations
The Art of Doctrine MigrationsRyan Weaver
 

More from Ryan Weaver (15)

Webpack Encore Symfony Live 2017 San Francisco
Webpack Encore Symfony Live 2017 San FranciscoWebpack Encore Symfony Live 2017 San Francisco
Webpack Encore Symfony Live 2017 San Francisco
 
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
 
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
 
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and moreSymfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
 
Symfony: Your Next Microframework (SymfonyCon 2015)
Symfony: Your Next Microframework (SymfonyCon 2015)Symfony: Your Next Microframework (SymfonyCon 2015)
Symfony: Your Next Microframework (SymfonyCon 2015)
 
Guard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful SecurityGuard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful Security
 
Grand Rapids PHP Meetup: Behavioral Driven Development with Behat
Grand Rapids PHP Meetup: Behavioral Driven Development with BehatGrand Rapids PHP Meetup: Behavioral Driven Development with Behat
Grand Rapids PHP Meetup: Behavioral Driven Development with Behat
 
Master the New Core of Drupal 8 Now: with Symfony and Silex
Master the New Core of Drupal 8 Now: with Symfony and SilexMaster the New Core of Drupal 8 Now: with Symfony and Silex
Master the New Core of Drupal 8 Now: with Symfony and Silex
 
Silex: Microframework y camino fácil de aprender Symfony
Silex: Microframework y camino fácil de aprender SymfonySilex: Microframework y camino fácil de aprender Symfony
Silex: Microframework y camino fácil de aprender Symfony
 
Drupal 8: Huge wins, a Bigger Community, and why you (and I) will Love it
Drupal 8: Huge wins, a Bigger Community, and why you (and I) will Love itDrupal 8: Huge wins, a Bigger Community, and why you (and I) will Love it
Drupal 8: Huge wins, a Bigger Community, and why you (and I) will Love it
 
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other ToolsCool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
 
The Wonderful World of Symfony Components
The Wonderful World of Symfony ComponentsThe Wonderful World of Symfony Components
The Wonderful World of Symfony Components
 
A PHP Christmas Miracle - 3 Frameworks, 1 app
A PHP Christmas Miracle - 3 Frameworks, 1 appA PHP Christmas Miracle - 3 Frameworks, 1 app
A PHP Christmas Miracle - 3 Frameworks, 1 app
 
Doctrine2 In 10 Minutes
Doctrine2 In 10 MinutesDoctrine2 In 10 Minutes
Doctrine2 In 10 Minutes
 
The Art of Doctrine Migrations
The Art of Doctrine MigrationsThe Art of Doctrine Migrations
The Art of Doctrine Migrations
 

Recently uploaded

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 

Recently uploaded (20)

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 

Being Dangerous with Twig (Symfony Live Paris)

  • 1. Symfony Live 2011 being dangerous with Twig a short story by Ryan Weaver March 4th, 2011
  • 2. being dangerous with Twig A 5-step guide to using Twig – the fast, secure and extensible PHP templating engine – to create clean template code, leverage powerful filters, make your designers write you love letters, write template functions that don't clog up your global PHP namespace, take advantage of true template inheritance, hang out with Django programmers and be able to talk template syntax, enjoy true and non- invasive output escaping, have more time for your family, control whitespace, add global variables to all templates, stop lying when you try to tell yourself that <?php echo looks better than a simple {{, use the fancy for-else control, Rock some macros – little reusable code functions, do awesome stuff like “{% if i is divisibleby 2 %}”, mediate in the simplicity of your templates and drink more green tea, sandbox your template and whitelist capabilities – allowing Twig to be used in a CMS, take advantage of the fact that all templates compile to PHP classes that can extend a base class of your choosing, impress your friends by changing the print tag from {{ var }} to [all-your-base] var [are-belong-to-us], confuse the guy next to you by changing “is” and “is not” to mean the opposite things and convince him that he's misunderstood how logical expressions are used in programming languages all along, create a custom tag that takes the body of its block and tweets it, write templates the expresses presentation and not program logic. Ryan Weaver Symfony Live 2011
  • 3. @weaverryan » symfony » symfony documentation » collaboration » the lovely @leannapelham
  • 4. iostudio: flying the symfony flag ● Advertising & Integrated Marketing Solutions • coming to you from » Nashville, TN » Washington, D.C. • 150 employees • and we're hiring!
  • 5. act 1 Why Twig?
  • 7.
  • 8. Template engines A template engine allows you to render a presentation (HTML, XML, etc) via a template in a controlled environment It should allow special functionality that makes creating templates easier (helpers, template inheritance, etc)
  • 9. a template engine is a tool
  • 10. why not just render PHP templates?
  • 11. PHP templating woes » rendering template files is a hack: an include statement with output-buffering control » no or faked template inheritance » no isolation: PHP templates suck in any global variables or functions available
  • 12. we need the brevity of templates with the isolation of object-oriented programming
  • 13. so give me some Twiggy pudding Twig is: Twig offers: » fast » true inheritance » flexible » real output escaping » concise » tons of filters » secure » custom tags » fully-featured » great documentation » Extensible » global variables » designer-friendly » the “for-else” control http://www.twig-project.org
  • 14. Twig is concise and each template compiles to an actual PHP object
  • 16.
  • 17.
  • 18.
  • 20. “The template system is meant to express presentation, not program logic.” - Django documentation
  • 21. Twig can easily be used anywhere
  • 22.
  • 23. act 2 Twig's simple life
  • 24. Twig's three tags Twig parses just three simple tags: » comment tag » print tag » block tag
  • 25. a. do nothing (comment tags) {# comment #} » totally ignored when rendered
  • 26. b. say something (print tags) {{ 'print me!' }} » prints the given expression » think “<?php echo” » If you're ultimately printing something, use this tag
  • 27. c. do something (block tags) {% set foo = 'inside a block tag' %} » used mostly for control-flow statements like if, for, include and block » can have beginning and end tags » if you're *doing* something and not *printing* something, use this tag
  • 28. Twig's three tags » do nothing: {# comment tag #} » say something: {{ print tag }} » do something: {% block tag %} it's just that simple
  • 29. act 3 Everything is an expression
  • 30. expressions: Twig guts » like PHP, most everything inside a tag is an expression » expressions are the most interesting and flexible part of Twig
  • 31. Expressions Block names Block-specific tokens
  • 32. an expression can consist of many different things
  • 33. strings, variables, arrays, functions, filters, tests, subscripts...
  • 34. strings, numbers and variables » like any language, strings, numbers and variables are commonplace
  • 35. arrays and hashes » arrays use [], hashes use {}
  • 36. operators » twig has operators just like PHP, but extensible and with some extras
  • 37. filters » a filter always follows a pipe (|) and modifies the value that precedes it » a filter may or may not take arguments
  • 38. functions » just like PHP, returns a value based on some input
  • 39. twig expresses himself » strings, numbers and variables » arrays and hashes » operators » filters » functions hey – it's simple like PHP, but flexible...
  • 40. act 4 twig on the battlefield
  • 41. the test... » a template that displays a list of “widgets” in odd-even rows » render tags and other info about each widget » create basic, clean pagination
  • 45. filter to title-case the widget name filters to strip tags and shorten the widget's description
  • 46. your presenter is lying to you... » the “truncate” filter isn't part of Twig, but is available via a repository of extensions » Everything in Twig is loaded via an Extension (even the core stuff) » Extensions are easy to use and create – we'll prove it later * https://github.com/fabpot/Twig-extensions
  • 47. odd/even classes like a boss “really easily”
  • 48. Twig function cycles through the given array items Special variable available inside all “for” loops. The “loop” variable knows other tricks like “loop.last” and “loop.revindex”
  • 50. apply the date filter chain filters to turn a list of tags into a comma-separated list
  • 54. function returns a positive radius of numbers around the center (e.g. 3, 4, 5, 6, 7) the awesome loop variable tells us when we're in the last iteration
  • 55. the audacity: your speaker just lied again » but.... the “radius” function doesn't actually exist in Twig. but since it's pretty handy, let's create it!
  • 56. act 5 Twig extensions
  • 57. Twig extensions everything in Twig is loaded by an “Extension” class: » filters » functions » operators » tests (e.g. divisbleby) » custom tags Extensions are EASY!
  • 58. step 1: create a class that extends Twig_Extension
  • 59. step 2: tell Twig about the extension
  • 60. step 2: tell Twig about the extension (Symfony2) * don't forget to import this file from your application's configuration (i.e. app/config/config.yml)
  • 61. step 3: add some guts to the extension class
  • 62. step 4: Celebrate!!! * buy a round of drinks * watch the sun set * ask a cute stranger out to dinner
  • 63. I want more! ok great – do some reading! » http://www.twig-project.org/doc/advanced.html » http://www.twig-project.org/doc/extensions.html seriously – the Twig docs are quite excellent
  • 64. act 6 after-dinner mint mmm
  • 65. screw with the Twig syntax » because Twig is totally sandboxed (i.e. you control exactly what can and cannot be done inside a template, Twig is a perfect fit for a CMS. » and if Twig's syntax scares your clients... change it!
  • 66.
  • 67. cool, what about debugging? a debug tag ships with the twig-extensions
  • 68. the “debug” extension is available for you in Symfony2 - just enable it
  • 69. prints every variable available prints the foo variable
  • 70. but we've only just scratched the surface
  • 71. there's much much more » inheritance name can be: * an item on an array * property on an object » macros (reusable code bits) * getName() » subscripts or you can force it to *just* fetch “name” as an array item
  • 72. Twig, he's a people-person » Twig loves contributions, so *get involved*! » https://github.com/fabpot/twig » https://github.com/fabpot/twig-extensions » http://groups.google.com/group/twig-users
  • 73. The Symfony documentation wants you! » The Symfony2 documentation is a community effort » The best way as a beginner to get involved immediately! » Talk to me!!!
  • 74. thank you Ryan Weaver iostudio @weaverryan www.thatsquality.com ryan [at] thatsquality.com *do* reach out to me – i'd love to talk nerd with you comments, feedback, questions http://joind.in/2765