Bonswouar
Bonswouar

Reputation: 1590

Twig : Add JS file from included template

I've got my main layout with a {% block javascript %}. A template is extending it. In this template, I've included my menu bar.. But in this menu bar, in some cases (depending of the parameters when I include it) it needs a special JS file.

But I can't access a block from an included template apparently. What can I do, instead of having to include it in every templates using this special menu bar ?


EDIT :

Here is some of my code.

The layout :

<!DOCTYPE html>
<html>
    <head>
    {# ... #}
        {% block stylesheets %}
           {# ... #}
        {% endblock %}
    {# ... #}
    </head>
    <body id="bodyLayout">
        {# ... #}
        {% block content %}
        {% endblock %}
        {% block javascripts %}
        {# ... #}
        {% endblock %}
    </body>
</html>

One of the templates :

{% extends "CDASvBundle:Default:layout.html.twig" %}
{# ... #}
<div class="col-sm-8">
  {% include 'CDASvBundle:Default:blocs-droite.html.twig' with {blocs : "lesPlusContrats"}  %}
</div>

The CDASvBundle:Default:blocs-droite.html.twig template :

{# ... #}
{% elseif blocs == 'Aide' %}
    <a href="" data-toggle="modal" data-target="#rappel">› Rappelez-moi</a>
    {% include 'CDASvBundle:Component:rappelez-moi-popup.html.twig' %}
{% endif %}

And the 'CDASvBundle:Component:rappelez-moi-popup.html.twig :

<!-- Modal -->
<div class="modal fade" id="rappel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
{# ... #}
</div><!-- /.modal -->

To make it work it needs a special JS file, which contains some AJAX and other little things.

But I often ear it's not clean to write some JS in the middle of an HTML page, so I'd like to include this JS file at the end using the javascripts block from the main layout. Here is my problem !

Upvotes: 2

Views: 1976

Answers (1)

Jim D
Jim D

Reputation: 978

If I understand your question correctly, you should be able to extend the parent block from the extending template like so:

{% block javascript %}
    {{ parent() }}
    {# Your other JavaScript files here #}
{% endblock %}

Give that a shot. Here's an example from the docs.

{% extends "base.html" %}

{% block title %}Index{% endblock %}
{% block head %}
    {{ parent() }}
    <style type="text/css">
        .important { color: #336699; }
    </style>
{% endblock %}
{% block content %}
    <h1>Index</h1>
    <p class="important">
        Welcome on my awesome homepage.
    </p>
{% endblock %}

Upvotes: 1

Related Questions