Awesomespeed

Articles, thoughts, photos, and video… by Dan Goodspeed

By

A basic “Hello, world” Twig templating install

I’m a big fan of templating for building websites. I also have a long history of building websites from scratch with no frameworks (comes with being a web developer for more than two decades).

Twig is an amazing templating system (which you can read about here) that I wanted to learn to start using on my sites, but I didn’t know where to start. Most developers use Composer to install Twig. I agree that it’s a good idea and a time-saver, but I like to be more hands-on when I’m teaching myself. Composer lets you skip some of these learning steps.

So I downloaded a Twig Install manually, intending to use it with my install of MAMP Pro. But it came with over 600 files and nowhere on the web (I searched for hours with no luck) does it say what to do with these files. So here it is, step-by-step instructions for a basic “Hello world” Twig install:

  1. Make a folder where you intend to save your project, naming it whatever you want.
  2. Download the latest Twig Install.
  3. Copy the “lib” folder from Twig Install into your project folder.
  4. Make two new folders in the project folder for the templates and the web home directory in the project folder. I called them “templates” and “web”. It works.
  5. Make a new template file in the templates folder, let’s call it “home.html” and make the contents just:

    Hello, {{ name }}!

    I’ve seen a variety of extensions used for the template files. “.tpl” and “.twig” are also common. I like “.html” because it’s mostly an HTML file and it’s easier for my text editor. You can use whatever, just be consistent.

  6. Make a new controller file in the “web” directory. A controller is pretty much a script that “controls” all other scripts. There’s plenty about them online so that’s all I’ll say about that. You can name this one “index.php” just so you don’t have to type the file name in the URL. Make this the contents of the file:

    <?php
    require_once("../lib/Twig/Autoloader.php" );
    Twig_Autoloader::register();
    $loader = new Twig_Loader_Filesystem('../templates/');
    $twig = new Twig_Environment($loader);
    echo $twig->render('home.html', array('name' => 'World'));

  7. In MAMP, make the “web” directory the root directory of a new virtual server.
  8. Go to the MAMP URL and you should see “Hello, World!”. And that’s your Twig install, ready to be built upon! I believe the resources to learn from there are pretty well documented online.

Leave a Reply