Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

symfony - Extends parent blocks from embed template

I would like to inject inside the styles and scripts blocks in my layout new values, but from the embed block. Of course it throws the error Calling "parent" outside a block is forbidden.. Is there any workaround ?

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 %}

(And I cant/wont use the blocks scripts and styles inside the list.html.twig. They are part of the datatable template, it will not make any sens to define theme in the list.html.twig.). And sadly I cant use use because this function does not support dynamics properties, only strings.

From the doc :

Because use statements are resolved independently of the context passed to the template, the template reference cannot be an expression.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As said in the comment, includes/embeds can't alter blocks from their includer. That said there is an extension available that could solve your problem.

This Deferred Twig Extension can be found here

Basically the node postpones the execution of a said block. This way you can create a variable that holds all of your javascript links and output them. This can be seen in the advanced example found on the github.

credits to Eugene Leonovich for making this extension


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...