by
on
under
Permalink

Setting up Twig in Laravel


This week, I have been mostly trying… Laravel.

Trying a new PHP framework raises a few questions. What coding style does it use? How do you build models? What do templates look like?

When trying Laravel for the first time, I wasn’t keen on the Blade templating engine. So I decided to look for how to integrate Twig. One quick Google search later, and I found TwigBridge by Rob Crowe.

Following the instructions was simple enough. However, I think there was one thing missing. What do you name your template files so Twig can find them?

How to name Twig templates in Laravel

In Laravel, a Blade template for the “users” route would be called: users.blade.php

After a bit of experimenting, I found that the equivalent Twig template would be called: users.twig

This works out nicely in PhpStorm, as suddenly the file icon changed from a PHP file to a bit of green grass (maybe it looks better than a twig). And the code completion works. That’s much better than the last project I set up with Twig, which is on Zend Framework v1 and the files are named index.html.

Don’t forget to rename your base template to base.twig or similar. The Blade equivalent I created in the QuickStart guide was called layout.blade.php.

Comparing Blade and Twig templates

So, just for completeness, here’s a sample Blade template:

@extends('layout')
@section('content')
 @foreach($users as $user)
 <p>{{ $user->name }}</p>
 @endforeach
@stop

And here’s a Twig template:

{% extends "base.twig" %}
{% block content %}
{% for User in UserList %}
<p>{{ User.name }}</p>
{% endfor %}
{% endblock content %}

So far, I’m liking Laravel, but I’m much happier with Twig than Blade.

2 Comments

on “Setting up Twig in Laravel
2 Comments on “Setting up Twig in Laravel
  1. The Twig autocompletion from PhpStorm sounds helpful. I’m assuming it just autocompletes conditions and loops as opposed to variables and block names, etc?

    • Block names seem to work too. My example Twig template extends base.twig, which defines a single “content” block. With Twig autocompletion enabled, typing {% block and then the first letter of my named block displayed the word “content”. Handy!

      I haven’t been able to get autocomplete for variables, either those defined locally in Twig via {% set foo = ‘bar’ %} or object properties on the data I send to the view. I doubt it would pick up model data though, e.g. User.email.

Comments are closed.