从嵌入模板扩展父块 [英] Extends parent blocks from embed template

查看:30
本文介绍了从嵌入模板扩展父块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的布局中的样式和脚本块中注入新值,但是来自嵌入块.当然它会抛出错误在块外调用父"是被禁止的..有什么解决办法吗?

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

(我不能/不会使用 list.html.twig 中的块 scriptsstyles.它们是数据表的一部分模板,在 list.html.twig. 中定义主题没有任何意义.)遗憾的是我不能使用 use 因为这个函数不支持动态属性,只支持字符串.

(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.

来自文档:

因为 use 语句的解析独立于传递给模板的上下文,所以模板引用不能是表达式.

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

推荐答案

正如评论中所说,包含/嵌入不能改变包含器中的块.也就是说,有一个扩展程序可以解决您的问题.

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.

可以在这里找到这个Deferred Twig Extension

基本上节点会推迟所述块的执行.通过这种方式,您可以创建一个变量来保存所有 javascript 链接并输出它们.这可以在 advanced 示例中看到github.

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.

感谢 Eugene Leonovich 制作此扩展程序

credits to Eugene Leonovich for making this extension

这篇关于从嵌入模板扩展父块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆