0
Symfony Live 2011being dangerous with Twiga short story by Ryan WeaverMarch 4th, 2011
being dangerous with Twig     A 5-step guide to using Twig – the fast, secure and           extensible PHP templating engi...
@weaverryan    » symfony    » symfony documentation    » collaboration    » the lovely @leannapelham
iostudio: flying the symfony flag  ●      Advertising & Integrated Marketing Solutions  • coming to you from      » Nashvi...
act 1        Why Twig?
because templateengines are awesome
Template enginesA template engine allows you to render apresentation (HTML, XML, etc) via a templatein a controlled enviro...
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 ...
we need the brevity   of templateswith the isolation of  object-oriented   programming
so give me some Twiggy pudding Twig is:                  Twig offers:    » fast                    » true inheritance    »...
Twig is concise and each templatecompiles to an actual     PHP object
seeing is believing
a moment oftemplating zen
“The template system is meant toexpress presentation, not program             logic.”             - Django documentation
Twig can easily be used anywhere
act 2        Twigs simple life
Twigs three tagsTwig 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 youre ultimatel...
c. do something (block tags){% set foo = inside a block tag %}  » used mostly for control-flow statements like if, for,   ...
Twigs three tags  » do nothing: {# comment tag #}  » say something: {{ print tag }}  » do something: {% block tag %}   its...
act 3        Everything is an          expression
expressions: Twig guts  » like PHP, most everything inside a tag    is an expression  » expressions are the most interesti...
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 tak...
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 –...
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 widg...
Resources/views/Main/widgets.html.twiginside the SfLivePlayBundle
block tagprint tag
Lets clean things up
filter to title-case   the widget namefilters to strip tagsand shorten thewidgets description
your presenter is lying to you...   » the “truncate” filter isnt part of Twig, but     is available via a repository of ex...
odd/even classes   like a boss “really easily”
Twig function cycles throughthe given array items               Special variable available inside               all “for” ...
flex some filters
apply the date filterchain filters to turn a list of tagsinto a comma-separated list
convenience, readability
even managementknows 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 te...
the audacity: your speaker just lied again » but.... the “radius” function doesnt actually   exist in Twig.  but since its...
act 5        Twig extensions
Twig extensions everything in Twig is loaded by an “Extension” class:   » filters   » functions   » operators   » tests (e...
step 1: create a class that extends Twig_Extension
step 2: tell Twig about the extension
step 2: tell Twig about the extension (Symfony2)* dont forget to import this file from your  applications configuration (i...
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...
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 ...
cool, what about     debugging?a debug tag ships with the twig-extensions
the “debug” extension is available for youin Symfony2 - just enable it
prints every variable              availableprints the foo variable
but weve only justscratched the surface
theres much much more   » inheritance                   name can be:                                    * an item on an ar...
Twig, hes a people-person   » Twig loves contributions, so *get involved*!   » https://github.com/fabpot/twig   » https://...
The Symfony documentation wants you!  » The Symfony2 documentation is a community effort  » The best way as a beginner to ...
thank you                        Ryan Weaver                        iostudio                        @weaverryan           ...
Being Dangerous with Twig (Symfony Live Paris)
Being Dangerous with Twig (Symfony Live Paris)
Being Dangerous with Twig (Symfony Live Paris)
Being Dangerous with Twig (Symfony Live Paris)
Being Dangerous with Twig (Symfony Live Paris)
Being Dangerous with Twig (Symfony Live Paris)
Upcoming SlideShare
Loading in...5
×

Being Dangerous with Twig (Symfony Live Paris)

22,262

Published on

Twig - the PHP templating engine - is easy to use, friendly and extensible. This presentation will introduce you to Twig and show you how to extend it to your bidding.

Published in: Technology
2 Comments
35 Likes
Statistics
Notes
  • Hi Mykhailo!

    Yes, you're absolutely right! PHP templates definitely can do everything that Twig templates can do - it's a matter of choice and taste. Each does things a little bit different, but both are good choices.

    Also, I don't think developers are stupid - that's a pretty unfair statement :/ I really like Twig, but if you don't like it, that's totally fine :).

    Also, you *can* choose between Twig or normal PHP templates in Symfony, and all examples in the Symfony docs show both. I think there are two places where Twig is used internally by the framework (which I think is what you're referring to as the hard linking):

    1. The web debug toolbar & profiler - a debugging tool used locally

    2. Exception & error templates. This can be overridden by replacing the ExceptionController (http://symfony.com/doc/2.0/reference/configuration/twig.html#config-twig-exception-controller) and rendering a PHP template instead.

    I hope that helps! These tools are meant to make life simpler :)
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Any templating system written with a template language like PHP is evil. All you describing here is a fake. You are trying to concern is that all the developers are idiots, so you have to restrict them with something named Twig and telling them that 'you are as stupid as not allowed to use PHP inside templates, Twig is better for you'. I see no reason of doing something like:

    {% blablabla %}

    instead of



    Really NO MATTER! But the last one is a pure PHP code, no matter how it is implemented inside your framework - using of handling output buffering or not (yes, yes, it is possible to do without).

    Please, let user to choose what is better - to twig or not to twig. That's what I don't like in Symfony. I don't want my framework take decision. I want to choose which templating system to use. I like PHP, someone like Twig, someone wants to have Smarty (is it alive yet?)

    For the moment a have a big problem - I want to remove completely twig from a Symfony project and can not do it - because of hard linking of a framework and twig templating system. It's a nightmare...
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
22,262
On Slideshare
0
From Embeds
0
Number of Embeds
11
Actions
Shares
0
Downloads
232
Comments
2
Likes
35
Embeds 0
No embeds

No notes for slide

Transcript of "Being Dangerous with Twig (Symfony Live Paris)"

  1. 1. Symfony Live 2011being dangerous with Twiga short story by Ryan WeaverMarch 4th, 2011
  2. 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 dont clog up yourglobal PHP namespace, take advantage of true template inheritance, hang out withDjango programmers and be able to talk template syntax, enjoy true and non- invasiveoutput 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 hes 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. 3. @weaverryan » symfony » symfony documentation » collaboration » the lovely @leannapelham
  4. 4. iostudio: flying the symfony flag ● Advertising & Integrated Marketing Solutions • coming to you from » Nashville, TN » Washington, D.C. • 150 employees • and were hiring!
  5. 5. act 1 Why Twig?
  6. 6. because templateengines are awesome
  7. 7. Template enginesA template engine allows you to render apresentation (HTML, XML, etc) via a templatein a controlled environmentIt should allow special functionality thatmakes creating templates easier (helpers,template inheritance, etc)
  8. 8. a template engine is a tool
  9. 9. why not just render PHP templates?
  10. 10. 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
  11. 11. we need the brevity of templateswith the isolation of object-oriented programming
  12. 12. 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
  13. 13. Twig is concise and each templatecompiles to an actual PHP object
  14. 14. seeing is believing
  15. 15. a moment oftemplating zen
  16. 16. “The template system is meant toexpress presentation, not program logic.” - Django documentation
  17. 17. Twig can easily be used anywhere
  18. 18. act 2 Twigs simple life
  19. 19. Twigs three tagsTwig parses just three simple tags: » comment tag » print tag » block tag
  20. 20. a. do nothing (comment tags){# comment #} » totally ignored when rendered
  21. 21. b. say something (print tags){{ print me! }} » prints the given expression » think “<?php echo” » If youre ultimately printing something, use this tag
  22. 22. 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 youre *doing* something and not *printing* something, use this tag
  23. 23. Twigs three tags » do nothing: {# comment tag #} » say something: {{ print tag }} » do something: {% block tag %} its just that simple
  24. 24. act 3 Everything is an expression
  25. 25. expressions: Twig guts » like PHP, most everything inside a tag is an expression » expressions are the most interesting and flexible part of Twig
  26. 26. Expressions Block names Block-specific tokens
  27. 27. an expression can consist of many different things
  28. 28. strings, variables, arrays, functions, filters, tests, subscripts...
  29. 29. strings, numbers and variables » like any language, strings, numbers and variables are commonplace
  30. 30. arrays and hashes » arrays use [], hashes use {}
  31. 31. operators » twig has operators just like PHP, but extensible and with some extras
  32. 32. filters » a filter always follows a pipe (|) and modifies the value that precedes it » a filter may or may not take arguments
  33. 33. functions » just like PHP, returns a value based on some input
  34. 34. twig expresses himself » strings, numbers and variables » arrays and hashes » operators » filters » functions hey – its simple like PHP, but flexible...
  35. 35. act 4 twig on the battlefield
  36. 36. 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
  37. 37. Resources/views/Main/widgets.html.twiginside the SfLivePlayBundle
  38. 38. block tagprint tag
  39. 39. Lets clean things up
  40. 40. filter to title-case the widget namefilters to strip tagsand shorten thewidgets description
  41. 41. your presenter is lying to you... » the “truncate” filter isnt 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 – well prove it later * https://github.com/fabpot/Twig-extensions
  42. 42. odd/even classes like a boss “really easily”
  43. 43. Twig function cycles throughthe given array items Special variable available inside all “for” loops. The “loop” variable knows other tricks like “loop.last” and “loop.revindex”
  44. 44. flex some filters
  45. 45. apply the date filterchain filters to turn a list of tagsinto a comma-separated list
  46. 46. convenience, readability
  47. 47. even managementknows what this does
  48. 48. pagination?
  49. 49. function returns a positive radius of numbers around the center (e.g. 3, 4, 5, 6, 7)the awesome loop variable tells uswhen were in the last iteration
  50. 50. the audacity: your speaker just lied again » but.... the “radius” function doesnt actually exist in Twig. but since its pretty handy, lets create it!
  51. 51. act 5 Twig extensions
  52. 52. Twig extensions everything in Twig is loaded by an “Extension” class: » filters » functions » operators » tests (e.g. divisbleby) » custom tags Extensions are EASY!
  53. 53. step 1: create a class that extends Twig_Extension
  54. 54. step 2: tell Twig about the extension
  55. 55. step 2: tell Twig about the extension (Symfony2)* dont forget to import this file from your applications configuration (i.e. app/config/config.yml)
  56. 56. step 3: add some guts to the extension class
  57. 57. step 4: Celebrate!!!* buy a round of drinks* watch the sun set* ask a cute stranger out to dinner
  58. 58. 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
  59. 59. act 6 after-dinner mint mmm
  60. 60. 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 Twigs syntax scares your clients... change it!
  61. 61. cool, what about debugging?a debug tag ships with the twig-extensions
  62. 62. the “debug” extension is available for youin Symfony2 - just enable it
  63. 63. prints every variable availableprints the foo variable
  64. 64. but weve only justscratched the surface
  65. 65. theres 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
  66. 66. Twig, hes 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
  67. 67. 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!!!
  68. 68. thank you Ryan Weaver iostudio @weaverryan www.thatsquality.com ryan [at] thatsquality.com *do* reach out to me – id love to talk nerd with youcomments, feedback, questions http://joind.in/2765
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×