Slide 1

Slide 1 text

No content

Slide 2

Slide 2 text

Jonathan Reinink Software developer from Canada Been writing PHP for about 15 years Marketing agency for over a decade Started contract development this year Leadership group of The PHP League Wrote the Plates template library Wrote the Glide image library I <3 open source

Slide 3

Slide 3 text

Why do templates matter?

Slide 4

Slide 4 text

Templates often account for 25-50% of your overall code base.

Slide 5

Slide 5 text

Templates help separate your controller and domain logic from your presentation logic.

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

Templates are often developed by both server-side developers, and front-end developers.

Slide 8

Slide 8 text

Templates are always "spaghetti code". Because contain more than one language in the same file.

Slide 9

Slide 9 text

Bad template code contributes to technical debt.

Slide 10

Slide 10 text

Step 1: Choose the right template library.

Slide 11

Slide 11 text

People have very strong opinions about templating.

Slide 12

Slide 12 text

“This blog post is not for the faint- hearted! Some people will strongly disagree with me and some others will probably want to kill me at the upcoming Zend Conference.” —Fabien Potencier

Slide 13

Slide 13 text

“I'm not suggesting that native PHP templates are better than compiled templates (like Twig).” —Me

Slide 14

Slide 14 text

“oh... puts the pitchfork down” —Friendly Reddit reader “hides torch behind back…” —Another friendly Reddit reader

Slide 15

Slide 15 text

The native PHP vs compiled templates debate.

Slide 16

Slide 16 text

PHP is the oldest method of templating in PHP. (because PHP is a templating language)

Slide 17

Slide 17 text

!

Hello, =$name?>

!
    prepare("SELECT name FROM friends")) { $stmt->execute(); $stmt->bind_result($name); ! while ($stmt->fetch()) { echo '
  • '.$name.'
  • '; } } ?>

Slide 18

Slide 18 text

Important lesson: If your templates contain SQL code, you’re doing it wrong.

Slide 19

Slide 19 text

While PHP has evolved into a mature, object oriented language, it hasn’t improved much as a templating language.

Slide 20

Slide 20 text

Compiled templates fill this void by offering a new syntax specifically geared for templating.

Slide 21

Slide 21 text

{% extends "template.html" %} ! {% block title %}User Profile{% endblock %} ! {% block content %}

User Profile

Hello, {{ name }}

{% endblock %}

Slide 22

Slide 22 text

Since these compiled templates must be compiled, there is a slight performance hit.

Slide 23

Slide 23 text

You can write good template code with most modern templating libraries. Twig, Blade, Smarty, Moustache, Plates, Aura.View, Zend\View, etc…

Slide 24

Slide 24 text

I recommend you use Twig.

Slide 25

Slide 25 text

Choose a templating language with an easy learning curve. Easy for both server-side developers and front-end developers.

Slide 26

Slide 26 text

Compiled languages offer very simple, template oriented syntax. {{ var }}

Slide 27

Slide 27 text

  • No items found.
  • {% for item in items %}
  • {{ item }}
  • {% else %}
  • No items found.
  • {% endfor %} Native PHP Twig

    Slide 28

    Slide 28 text

    But, native PHP templates don’t have to be ugly.

    Slide 29

    Slide 29 text

    Always use the short echo syntax. =$user->name?>

    Slide 30

    Slide 30 text

    Never use blocks of PHP. name; } ?> =$user->name?>

    Slide 31

    Slide 31 text

    Only one statement per PHP tag. =$user->name?> =$user->name?>

    Slide 32

    Slide 32 text

    Never use curly brackets. =$user->name?> =$user->name?>

    Slide 33

    Slide 33 text

    Never using semicolons. =$user->name?>

    Slide 34

    Slide 34 text

    layout('template', ['title' => 'User Profile']) ?> !

    Hello =$this->e($name)?>

    !

    Friends

    !

    Invitations

    You have some friend invites!

    Slide 35

    Slide 35 text

    Avoid XML attribute based templating languages.

    Slide 36

    Slide 36 text

    Slide 37

    Slide 37 text

    Choose a templating language with syntax highlighting and auto- completion in your editor of choice.

    Slide 38

    Slide 38 text

    Always, always, always escape unsafe data.

    Slide 39

    Slide 39 text

    Hello, =$name?>

    Slide 40

    Slide 40 text

    Hello, Jonathan

    Slide 41

    Slide 41 text

    Hello, Click here

    Slide 42

    Slide 42 text

    Hello, <a href="http://xssattack.com/ ">Click here</a>gt;

    Slide 43

    Slide 43 text

    Hello, Click here

    Slide 44

    Slide 44 text

    Hello, =htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE)?>

    Slide 45

    Slide 45 text

    Hello, =$this->escape($name)?> Hello, =$this->e($name)?> Hello, =e($name)?>

    Slide 46

    Slide 46 text

    1. HTML escaping 2. HTML attribute escaping 3. CSS escaping 4. JavaScript escaping 5. URL escaping Be aware of the different types of escaping:

    Slide 47

    Slide 47 text

    If at all possible, use automatic escaping!

    Slide 48

    Slide 48 text

    Hello, {{ name }}

    Slide 49

    Slide 49 text

    Without automatic escaping, you MUST manually escape every single variable. And you will probably forget once in a while!!!

    Slide 50

    Slide 50 text

    It should also be VERY obvious in your templates when you are outputting raw data.

    Slide 51

    Slide 51 text

    Hello, {!! $name !!} Hello, {{ name|raw }} Blade Twig

    Slide 52

    Slide 52 text

    Automatic escaping is NOT possible in native PHP.

    Slide 53

    Slide 53 text

    =$this->name?>

    Attempt 1: Object overloading

    Slide 54

    Slide 54 text

    class Template { protected $values; ! public function __get($name) { return $this->escape( $this->values[$name] ); } }

    Slide 55

    Slide 55 text

    Problem: How do you escape object params and method calls?

    =$this->user->name?>

    Slide 56

    Slide 56 text

    Attempt 2: Object overloading with proxies

    =$this->user->name?>

    Slide 57

    Slide 57 text

    class Template { protected $values; ! public function __get($name) { return new TemplateProxy( $this->values[$name] ); } }

    Slide 58

    Slide 58 text

    class TemplateProxy { protected $value; ! public function __get($name) { return new TemplateProxy($this->name); } ! public function __call($name, $args) { return new TemplateProxy(...); } ! public function __toString() { return $this->escape($this->value); } }

    Slide 59

    Slide 59 text

    =$this->user->name?>

    Slide 60

    Slide 60 text

    No content

    Slide 61

    Slide 61 text

    Problems: double escaping, poor performance, horrible error debugging, collisions with template methods, etc, etc.

    Slide 62

    Slide 62 text

    Attempt 3: Compiled native php templates

    Slide 63

    Slide 63 text

    =$name?>

    =$this->escape($name)?>

    Pre-compilation: Post-compilation:

    Slide 64

    Slide 64 text

    No content

    Slide 65

    Slide 65 text

    Automatic escaping is NOT possible in native PHP.

    Slide 66

    Slide 66 text

    Watch your whitespace, this isn’t the Wild Wild West.

    Slide 67

    Slide 67 text

    Always use tabs, or always use spaces, NEVER MIX.

    Slide 68

    Slide 68 text

    Watch your indenting.

    Slide 69

    Slide 69 text

      {% for item in items %}
    • {{ item }}
    • {% else %}
    • No items found.
    • {% endfor %}

    Slide 70

    Slide 70 text

    Use comments that only appear in the template, not the rendered markup.

    Slide 71

    Slide 71 text

    {# This is a Twig comment #}

    Slide 72

    Slide 72 text

    Your templates should be very low on logic.

    Slide 73

    Slide 73 text

    Templates are not responsible for data lookup, persistence or other complex tasks.

    Slide 74

    Slide 74 text

    Anything outside of conditionals, loops and basic formatting is a code smell.

    Slide 75

    Slide 75 text

    Watch your control structures. Use: if, for, foreach Don’t use: switch, while, do-while

    Slide 76

    Slide 76 text

    So what exactly is basic formatting then? • Date formatting • Case changes • String concatenation • String trimming • Number formatting • URL encoding

    Slide 77

    Slide 77 text

    Consider using a logic- less templating language.

    Slide 78

    Slide 78 text

      {{# users }}
    • {{ name }}
    • {{/ users }}

    Slide 79

    Slide 79 text

    namespace App\ViewModels; ! class UsersViewModel { public function users() { return [ ['name' => 'Jonathan'], ['name' => 'Amy'], ['name' => 'Joey'], ]; } }

    Slide 80

    Slide 80 text

    Some template logic is okay, but only if it’s presentation logic.

    Slide 81

    Slide 81 text

    Avoid accessing the global namespace.

    Slide 82

    Slide 82 text

    @if (Request::is('/')) Home @else Home @endif

    Slide 83

    Slide 83 text

    @if ($url === '/') Home @else Home @endif

    Slide 84

    Slide 84 text

    Preassign template data instead of accessing global variables.

    Slide 85

    Slide 85 text

    $templates->addData(['url' => $url], 'header');

    Slide 86

    Slide 86 text

    view()->composer('header', function ($view) { $view->with('url', $url); });

    Slide 87

    Slide 87 text

    $twig->addGlobal('url', $url);

    Slide 88

    Slide 88 text

    Use the dot notation for variable resolution. object.parameter Access arrays, objects and methods the same way.

    Slide 89

    Slide 89 text

    {{ user.name }} = $user['name'] {{ user.name }} = $user->name {{ user.name }} = $user->name()

    Slide 90

    Slide 90 text

    Templates should only know about one instance variable.

    Slide 91

    Slide 91 text

    Rule #4: Controllers can instantiate only one object. Therefore, views can only know about one instance variable and views should only send messages to that object. — Sandi Metz, rules for developers

    Slide 92

    Slide 92 text

    Keep your templates as short as possible. Break templates into smaller, reusables pieces.

    Slide 93

    Slide 93 text

    insert('partials/header') ?> !

    Your page content.

    ! insert('partials/footer') ?>

    Slide 94

    Slide 94 text

    insert('partials/header', ['title' => 'Home']) ?> !

    Your page content.

    ! insert('partials/footer') ?>

    Slide 95

    Slide 95 text

    {% include 'partials/header.html' with {'title': 'Home'} %} !

    Your page content.

    ! {% include 'partials/footer.html' %}

    Slide 96

    Slide 96 text

    Don't be afraid to repeat (very) small pieces of code.

    Slide 97

    Slide 97 text

    value="=$user->id?>"> =$user->name?>

    Slide 98

    Slide 98 text

    =$user->name?> =$user->name?>

    Slide 99

    Slide 99 text

    Use inheritance for even better organization of templates.

    Slide 100

    Slide 100 text

    template.html {% extends "template.html" %} ! {% block title %}Profile{% endblock %} {% block content %}

    Profile

    Hello, {{ name }}

    {% endblock %} profile.html {% block title %} Default title {% endblock %} ! {% block content %}

    Default content

    {% endblock %} !

    Slide 101

    Slide 101 text

    Use a templating language that you can extend.

    Slide 102

    Slide 102 text

    $templates->registerFunction('upper', function ($string) { return strtoupper($string); });

    Hello =$this->upper($name)

    Slide 103

    Slide 103 text

    Blade::directive('datetime', function ($expression) { return "format('m/d/Y H:i'); ?>"; }); @datetime($blog->publish_date)

    Slide 104

    Slide 104 text

    Use a template language that’s easy to debug.

    Slide 105

    Slide 105 text

    Use a template language that offers a sandbox mode.

    Slide 106

    Slide 106 text

    Use a template language that performs well. Hint: they basically all do.

    Slide 107

    Slide 107 text

    Automatic escaping is WAY more important than the speed advantage of native PHP templates.

    Slide 108

    Slide 108 text

    Follow me on Twitter at @reinink Rate this talk joind.in/15753 Thanks!