To my understanding, by using twig's extends
method, it should be possible to add code to the footer from within a template that is included anywhere else.
Like if we render the main page and have a <form>
there in a template edit_form.html.twig
and we know we need special javascript here (only for that form) so we decide to add this javascript tags in the footer at the end of the page like this:
edit_form.html.twig
{% block edit_form %}
<form id="editForm">
<!-- form html here -->
</form>
{% endblock edit_form %}
{{ include('edit_form_js.html.twig') }}
We want this javascript to be at the end of the page:
edit_form_js.html.twig
{% extends "footer.html.twig" %}
{% block js %}
{{ parent() }}
<script>
// special js code only needed for the <form>
</script>
{% endblock js %}
footer.html.twig
{% block js %}
<script src="jquery.js"></script>
{% endblock js %}
But doing this does not add the custom form javascript at the end after the jquery inclusion but results in the block js
being twice on the page (after the form and in the footer)
Is my understanding of twigs extends
wrong?
Included templates don't know anything from the template it's being called from. Therefor an included template cannot alter a block from that said template. You might want to have a look at the deferred extension