A Front End Developer’s Perspective on Twig

In web development, the process of transferring marked-up pages from front end to back end developers often poses certain difficulties.

Problems arise mostly when back end developers try to convert a markup into templates for their own needs.

Fortunately, today this kind of problem can be easily solved by means of MV* (MVC) Frameworks where the work with views is carried out only by front end developers.

But what shall we do when the project isn’t written in AngularJS or BackboneJS? For that, we came up with the solution to use Twig – a modern template engine for PHP programming (http://twig.sensiolabs.org). It is the most flexible, fast, and secure template engine for PHP.

One more issue I’d like to share, from my experience, lies in the way of testing the work result. Working with Twig, you have to launch a local server based on PHP by default. This might be very inconvenient for front end developers. Fortunately, there’s a solution for avoiding it. This can be accomplished with a combination of nodeJS (http://nodejs.org/) and task runner – gulpJS (http://gulpjs.com).

Gulp and Yeoman Installations

In case you haven’t used nodeJS yet, you’ll have to install it on your computer. After the installation of nodeJS, you have to install gulp globally. This can be easily done – just write the following text in the command line:

$ npm install --global gulp

In addition, you’ll have to install Yeoman for further work (http://yeoman.io). It helps to make our webapp generation agile and high quality.

$ npm install -g yo

Project build up

The next step will be generating our project, where I suggest to use an open-source generator (https://github.com/yeoman/generator-gulp-webapp), that scaffolds out a front-end web app using http://gulpjs.com for the build process.

Install the generator:

$ npm install --global generator-gulp-webapp

And now run $ yo gulp-webapp to scaffold your webapp

Afterward, you have to deliver the application package https://www.npmjs.com/package/gulp-twig (https://www.npmjs.com/package/gulp-twig) based on twig.js. Twig.js is a pure JavaScript implementation of the Twig PHP templating language.

Twig Installation

This method demonstrates how to set upTwig as your HTML template engine:

1. Install

$ npm install gulp-twig --save

2. Create a views task

Add this task to your gulpfile.js, it will compile .twig files to .html files in .tmp:

Go ahead and test it. It’s one of the easiest ways to work without PHP. In addition, we gain live reload during the work which is very convenient because there’s no need to reload the web page manually.