4
votes

I'd like to include a widget in different pages and have the related scripts, defined in this sub-template, happened automatically at the end of the page with the other scripts without having to do several includes.

I tried to use a block in an included sub-template and add some script in that block defined itself in base.html.twig so those scripts would load at the end of the page.

In base.html.twig I have

<html><body>
   <div>{% block content %}{% endblock %}</div>
   <aside>{% block aside %}{% endblock %}</aside>
   ...
   {% block javascripts %}
      <script src="..."></script>
      <script src="..."></script>
      ...
   {% endblock %}
   {% block widgetInlineScript %}{% endblock %}
</body></html>

I have a template profile.html.twig which extends base.html.twig and looks so

{% extends '::base.html.twig' %}
{% block content %}
   ...
{% endblock %}
{% block aside %}{% include 'ApplicationRcBundle:include:promo/adSpace_topRight.html.twig' %}{% endblock %}

In include/widget.html.twig I couldn't use {% block javascripts %}{{ parent() }} ... because it doesn't extend anything itself so using parent() fail. Instead I used a specific block.

{% block widgetInlineScript %}
<script type="text/javascript" id="widgetInlineScript" >
...
</script>
{% endblock %}

Twig compile the template well but render the script in the DOM just after the widget instead of rendering it in place of {% block widgetInlineScript %} at the end of the page.

So is it possible to use a block inside an included subtemplate ? Thanks

1
What's the problem? Twig is defined this way (an include has its own scope otherwise it would be hard to maintain). You could create another template with the javascript in it and include it in the block widgetInlineScript (like you did for the aside block).Thomas Potaire
Thanks Thomas but the purpose was to test if its possible to include a widget in different pages and have the related scripts, defined in it, happened at the end of the page with the other scripts.svassr
@svassr I see your conflict now, do you really need to render at the end? How big is the script?MGP
Not that big (about 130 lines) so I'm considering to separate it from the widget and bring it to the base js collection in base.html.twig so it's available everywhere.svassr
I also tried to define a twig global variable which I treat like an array and merge all the widgets scripts to finally loop on this array and dump all the script at the end of teh page. But As you said the include has it's own scope and even if I'm able to set the value it's not available in base.html.twig's scope.svassr

1 Answers

2
votes

I answered similar question today:

Append content to block from multiple subtemplates

Basically I created blocks using the "Horizontal reuse" technique:

{% use "blocks.html" with sidebar as base_sidebar %}

You can check the doc here:

http://twig.sensiolabs.org/doc/tags/use.html