Fix ‘A template that extends another one cannot have a body in …’ in Twig with Symfony2

This may be a confusing error at first but it’s quite self explanatory. You can’t have any HTML text in a Twig template that extends another, not even comments.

Twig_Error_Syntax

So for example this would raise the error:

<!-- src/Acme/DemoBundle/Resources/views/Default/index.html.twig -->
{% extends 'AcmeDemoBundle::layout.html.twig' %}

{% block stylesheets %}
  {{ parent() }}
  <link rel="stylesheet" href="{{ asset('bundles/demo/css/base.css') }}" type="text/css" media="all" />
{% endblock %}

The solution: delete the HTML comment in the first line or use Twig comments:

{# src/Acme/DemoBundle/Resources/views/Default/index.html.twig #}
{% extends 'AcmeDemoBundle::layout.html.twig' %}

{% block stylesheets %}
  {{ parent() }}
  <link rel="stylesheet" href="{{ asset('bundles/demo/css/base.css') }}" type="text/css" media="all" />
{% endblock %}

You might also like

Twig-extensions in Symfony2
Twig comes with multiple filters that provide functions like round, slice, sort, etc. In case you need...

Add Twig syntax highlight in Sublime Text 2
Select the "Preferences->Browse Packages..." menu to open the folder that contains Sublime Text 2 packages. Download...

Symfony Forms and Bootstrap Datetimepicker
In this example I'm going to use the spanish locale and the "Europe/Madrid" timezone.First we need...

Expose config.yml values globally for Twig templates in Symfony2 applications
Lets suppose you have created a bundle that has some specific configuration in the config.yml file (this...

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.