Search code examples
symfonytwigblock

call block in second parent layout.twig.html symfony2


I want to execute a javascript in when user enter in this page : page1.twig.html

    {% extends "Test1Bundle::layout1.html.twig" %}

   // block code javascript here

    {% block content %}
    <div>
        <span>Alexa .</span>
    </div>
    {% endblock %}

layout1.html.twig :

{% extends 'Test1Bundle::layout2.html.twig' %}
<p>
My name is : {% block content %}{% content %}
</p>

layout2.html.twig :

<!DOCTYPE html>
<html lang="fr">
<head>
// call block javascript here
</head>
.
.
.

I don't know what I do for this and which function to use ! please help !


Solution

  • You need to define empty blocks in your parents, where you want to see your stuffs rendered:

    page1.html.twig:

    {% extends "layout1.html.twig" %}
    
    {% block script %}
    
     <script type="text/javascript">
       // whatever
     </script>
    
    {% endblock %}
    
    {% block name %}
    <div>
        <span>Alexa .</span>
    </div>
    {% endblock %}
    

    layout1.html.twig:

    {% extends 'layout2.html.twig' %}
    {% block content %}
    <p>
    My name is : {% block name %}{% endblock %}
    </p>
    {% endblock %}
    

    layout2.html.twig:

    <!DOCTYPE html>
    <html lang="fr">
    <head>
       {# btw, scripts are better at the bottom of the body #}
       {% block script %}{% endblock %}
    </head>
    <body>
       {% block content %}{% endblock %}
    </body>
    </html>
    

    See fiddle