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.
P粉3333954962023-12-21 11:48:45
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 delayed Twig extension
can be found here
Advanced examples on github.
Thanks Eugene Leonovich for making this extension