Twig!

Super-Charged Themes with a Template Language

Jared Novack

@jaredNova

  • What's a Template Language?
  • What is Twig?
  • What YOU can do with it

Good news!

PHP is a template language!

...from 1995


var personSlug = sanitizeName(person.name);
var string = '
'; string += '

'+person.name+'

'; string += ''+person.name+' headshot'; string += '
    '; for (var i = 0; i < person.favoriteMovies.length; i++) { string += '
  • ' + person.favoriteMovies[i] + '
  • '; } string += '
';

The Template Language says...

  • Take your markup
  • Add the variables
  • And Handlebars will do the rest

George Costanza

George Costanza headshot
  • Death Blow
  • Chunnel
  • Cry, Cry Again

{{name}}

{{name}} headshot
    {{#each favoriteMovies}}
  • {{this}}
  • {{/each}}

George Costanza

George Costanza headshot
  • Death Blow
  • Chunnel
  • Cry, Cry Again

var personSlug = sanitizeName(person.name);
var string = '
'; string += '

'+person.name+'

'; string += ''+person.name+' headshot'; string += '
    '; for (var i = 0; i < person.favoriteMovies.length; i++) { string += '
  • ' + person.favoriteMovies[i] + '
  • '; } string += '
';

Turns out this is a lot easier

  • JSRender
  • dust.js
  • Transparency
  • dom.js
  • doT.sj
  • EJS
  • Handlebars
  • Hogan.js
  • ICanHaz.js
  • Jade templates
  • JSRender
  • Mustache
  • Nunjucks
  • Plates.js
  • Pure.js
  • Underscore Templates
  • Craft
  • Drupal
  • ExpressionEngine
  • Laravel
  • Symfony
  • You can do anything (it just might take a really long time)
  • Oh God, Don't Change Anything!
  • You run-out of time for the little extras

It's not fun

Twig to the rescue!

  • Craft
  • Drupal
  • ExpressionEngine
  • Laravel
  • Symfony

Problem: function stew

  • <?php get_the_title(); ?>
  • <?php get_the_content(); ?>
  • <?php get_permalink(); ?>
  • <?php get_post_custom($id, 'my-field', true); ?>

<?php
$thumb_id = get_post_thumbnail_id($post->ID);
$url = wp_get_attachment_url($thumb_id);
?>
<img src="<?php echo $url; ?>" 
alt="Thumbnail for <?php echo $post->post_title; ?>" />
						

Solution: object-based code

[show getting a thumbnail, title and permalink on a single page]

Problem: keeping templates neat

Solution: Filters!

Problem: looping

Problem: inclusion

Problem: Linear Page Construction

Solution: Template Inheritance and Extension

In conclusion...

Twig: twig.sensiolabs.org

Timber: timber.upstatement.com

(The slides will be posted as soon as
I can get an SSH connection to GitHub)

THE END

By Jared Novack / upstatement.com