Frontend Templating with Gulp and Twig.js

Save time in your frontend development workflow by using the power of of a frontend templating language, like Twig.js! Twig.js is a javascript port of the popular PHP templating language, Twig, by Sensio Labs. Twig is also used by popular content management systems, such as Craft CMS. If you develop websites with Craft CMS, you'll feel right at home building static fronted templates with Twig.js.

Why use a frontend templating language?

There are many reasons to use a frontend templating language. I always build my frontend templates before I transition into any sort of backend development. Having access to simple features during the frontend build such as extending layouts, including partials, and using variables and loops means I can be much more efficient with my workflow. Here are some things types of projects I've used a frontend templating workflow for:

  • Building and launching a small, static website
  • Delivering complete, frontend templates to a separate team of backend developers
  • Prototyping complex application flows or responsive websites, which often need to be tested across multiple devices
  • Prepping and testing frontend templates before transitioning into CMS development
  • Exploring and defining complex data models that will need to be developed on the backend

Meet Twig.js

Twig.js is just a Javascript implementation of the Twig templating language for PHP. It has many of the basic features avaialble in Twig, such as template layouts, includes, variables, loops, conditionals etc. With a build tool like Gulp, we can get started on some of the easy templating work early, saving us time and mental energy when it's time to integrate backend.

How to add Twig.js to your frontend workflow?

Let's dive in and get Twig.js added to our Gulp build process. If you're not already using Gulp in your project, see my article about quickly adding Gulp to your project.

If you're using Grunt, there's an equivelent template parser available for that as well, but I won't be covering how to set up the Grunt tasks in this article.

1. Install the gulp-twig NPM package

Open terminal and go to the root folder of your project (wherever your gulpfile.js and node_modules folder are located). Then type the following:

> npm install gulp-twig --save-dev

2. Add Twig to your gulpfile

Now we need to tell our gulpfile about Twig.js. Add the following line toward the top of your gulpfile.js file near where you require Gulp and other packages.

var twig = require('gulp-twig');

3. Create a task in your gulpfile for parsing Twig templates

Now, we can set up our gulp task for compiling our Twig.js templates to HTML so we can see our rendered templates in the browser during the frontend development phase. We will be running the task on HTML files with the Twig syntax and outputting the rendered results to a destination directory.

Here's a basic example of a project with a source and destination directory, where "src/" will hold our Twig templates, and "dist/" will eventually contain our HTML templates. Your project may be set up a little differently, so tweak the directory names as needed.

dist/
src/
   twig_template.html
node_modules/
gulpfile.js
package.json

Here's our Gulp task, which we've named "templates", that we'll be using to process our Twig templates. Add this to your gulpfile.js file.

// Compile Twig templates to HTML
gulp.task('templates', function() {
    return gulp.src('src/*.html') // run the Twig template parser on all .html files in the "src" directory
        .pipe(twig())
        .pipe(gulp.dest('dist')); // output the rendered HTML files to the "dist" directory
});

At this point, your gulpfile should look something like this, or at least contain the following:

var gulp = require('gulp');
var twig = require('gulp-twig');

// Compile Twig templates to HTML
gulp.task('templates', function() {
    return gulp.src('src/*.html') // run the Twig template parser on all .html files in the "src" directory
        .pipe(twig())
        .pipe(gulp.dest('dist')); // output the rendered HTML files to the "dist" directory
});

Now let's create a Twig template with some Twig syntax and parse it to a HTML file. Add a file to the src/ directory called twig_template.html with the following markup:

Now we should be able to run our named task in Terminal to parse our Twig template. Open Terminal, make sure you're in the same directory as your project's gulpfile.js file and run the following:

> gulp templates

If your task ran successfully, you should see your fully rendered HTML file with the same name in the dist/ directory. And you can now add the "templates" task to any your named Gulp tasks. For example, if you have a task called "build" which fires up a server and runs several other tasks, you might add the "templates" task to it like this:

gulp.task('serve', ['server', 'images', 'styles', 'scripts', 'templates']);

4. Template inheritance

Let's take it a step further and set up template inheritance so we don't have to duplicate the same HTML code on every template.

Create a folder in your src/ folder called layouts. Then create a file in your layouts/ folder called default.html. Your directory structure should look something like this now:

dist/
    twig_template.html
src/
    layouts/
        default.html
    twig_template.html
node_modules/
gulpfile.js
package.json

Copy all the wrapping HTML markup from your template and put it in default.html and set your content block area, just like you would for a Craft template.

Conents of default.html:

Then tell twig_template.html to extend from the default.html template and wrap the contents in our {% block content %} tag.

Contents of twig_template.html:

Now let's go back to Terminal and parse our Twig template.

> gulp templates

The rendered HTML file should have everything from default.html and twig_template.html.

Let's wrap things up by adding a simple include.

5. Includes

Let's add a new folder to our src/ folder called includes and a new file in our includes folder called header.html.

dist/
    twig_template.html
src/
    includes/
        header.html
    layouts/
        default.html
    twig_template.html
node_modules/
gulpfile.js
package.json

Move the heading from src/twig_template.html to the header.html and use an include instead.

Here's what header.html should look like:

And twig_template.html should look like this:

Let's run our "templates" gulp task one more time and see if it renders our include file.

> gulp templates

If it worked, you should see the content of your include file in your rendered HTML file.

Congrats! You can have now harnessed the power of Twig templating at the very beginning of your frontend development process! This will save you a ton of time during your frontend development phase and help you have a much smoother transition to backend development.

Advanced features

We've barely scratched the surface of what you can do with Gulp and Twig.js. Here are some other things you could consider adding to your frontend workflow with Gulp for different types of frontend development needs:

  • Use Browsersync to serve a static version of your templates to your browser, watch your template files for changes, and reload your browser when you make changes to them (And much more). If you haven't checked out Browsersync, you should.
  • Prettify your rendered HTML templates using gulp-prettify. This can be especially great if you're developing frontend templates that are meant to be handed off to another team. Get all the power of template inheritance and includes, and output beautiful HTML templates for your deliverables!
  • Use JSON files to set up real data for your templates using gulp-data. This can be handy for using more realistic data in your templates or prototypes. It can also be handy for modeling your data to save even more time before transitioning to CMS development.

If an advanced article on any of those topics interest you, tweet at me.

Do I have to use Twig.js?

Nope! There are other very similar frontend templating languages that you could use. Here are a few others.

Need help?

If you like the idea of saving your team tons of time on your frontend workflow, but hate the idea of tinkering with build tools like Gulp and Grunt, you're in luck. I can do it for you!

  • Modern frontend development setup - Hire me to set up a custom, modern and re-usable frontend build template for your Craft or ExpressionEngine projects.
  • Coaching and Mentoring - Have a new hire and want them rocking modern frontend workflow? I can combine one-on-one mentoring sessions with hand-picked online courses to ensure your new hire gets up to speed while you continue to focus on your business. Get in touch!
  • Hire me to help with a project - Just need someone to jump in and help with a project? I specialize in diving right in and adapting to your team's existing workflow. Along with slinging code, I can also offer helpful, time-saving strategies along the way. Book me for a project.
twitter Follow Share