I want to inject new values inside the style and script blocks in the layout, but from the embedded block.
Of course, it will throw an error Calling "parent" outside a block is forbidden.
.
Is there any solution?
layout.html.twig:
<!DOCTYPE html> <html> <head> {% block style %} <link rel="stylesheet" href="foo.css"> {% endblock %} </head> <body> {% block content "" %} {% block scripts %} <script src="foo.js"></script> {% endblock %} </body> </html>
list.html.twig:
{% extends 'layout.html.twig' %} {% block content %} {% embed datatable.html.twig %} {% block tbody %} <tr> <td>my awesome table</td> </tr> {% endblock %} {% endembed %} {% endblock %}
datatable.html.twig:
<table id="myDatatable"> <tbody> {% block tbody "" %} </tbody> </table> {% block styles %} {{ parent() }} <link rel="stylesheet" href="dataTables.css"> {% endblock %} {% block scripts %} {{ parent() }} <script src="dataTables.js"></script> {% endblock %}
(I can't/won't use scripts
and styles
inside the list.html.twig
block. They are part of the datatable template, in list.html.twig
.).
Unfortunately I can't use use
because this function doesn't support dynamic properties, only strings.
From the documentation:
Since use statements are parsed independently of the context passed to the template, template references cannot be expressions.
As mentioned in the comments, includes/embeds cannot change the block within its includer. That said, there is an extension available that may solve your problem.
This
Basically, the node delays the execution of said block. This way you can create a variable to hold all javascript links and output them. This can be seen in thedelayed Twig extension
can be found hereAdvanced examples on github.
Thanks Eugene Leonovich for making this extension