Extend parent block from embedded template
P粉033429162
P粉033429162 2023-12-20 21:08:59
0
1
463

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粉033429162
P粉033429162

reply all(1)
P粉333395496

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

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 the

Advanced examples on github.

Thanks Eugene Leonovich for making this extension

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!