Search code examples
symfonytwigtemplate-enginetemplatingtwig-extension

Use Include and Extends always showing error and can't be loaded


I have base.twig like this :

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=996">
        <meta name="description" content="{{ meta_description }}">
        <meta name="author" content="">
        <link rel="icon" href="{{ assets_url }}img/ico.png">
        <title>{{ meta_title }}</title>
        <link rel="stylesheet" href="{{ assets_url }}css/main.css">
        <script src="{{ assets_url }}js/jquery-1.11.3.min.js"></script>
        <script src="{{ assets_url }}js/plugin.js"></script>
        <script src="{{ assets_url }}js/main.js"></script>
    </head>
    <body>

        {% include 'partials/header.twig' %}

    </body>
</html>

I tried to import header.twig in base.twig but not working and still getting error message like this :

Fatal error: Uncaught Twig_Error_Syntax: A template that extends another one cannot include contents outside Twig blocks. Did you forget to put the contents inside a {% block %} tag? 

And this is header.twig file :

{% extends "base.twig" %}

<!-- my content header is here -->

What did i miss? What's wrong with my code ?, I read in https://twig.sensiolabs.org/doc/2.x/. Please give me solution or something. Thanks.


Solution

  • Just remove extending from header.html.twig. Read the documentation.

    Template which extends some parent template cannot be included in the parent, because there is an infinite loop. If you want to separate part of code, just split it to another twig and include it.

    But if you want to create independent template which bases on another then the template have to extends base.html.twig.

    E.g. articles.html.twig which extends base.html.twig, which has included header.html.twig.

    In code:

    base.html.twig

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
        </head>
        <body>
            {% include 'partials/header.html.twig' %}
    
            {% block body %}
            {% endblock %}
        </body>
    </html>
    

    header.html.twig

    <div>
       my header
    </div>
    

    articles.html.twig

    {% extends base.html.twig %}
    
    {% block body %}
        <div>
            articles content
        </div> 
    {% endblock %}
    

    Now, your rendered articles.html.twig from your controller, should look like:

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
        </head>
        <body>
            <div>
                my header
            </div>
    
            <div>
                articles content
            </div>  
        </body>
    </html>