在Twig模板Symfony中包含功能

时间:2022-10-24 14:20:26

Hello Guys I'm new to symfony and twig and what i'm trying to achiv is this:

大家好,我是symfony和twig的新手,我正在尝试achiv是这样的:

In my base.html.twig file I try to include('article.html.twig') all works fine until I try to override(extend) the stylesheets block that resides in base.html.twig from article.html.twig.

在我的base.html.twig文件中,我尝试包含('article.html.twig')一切正常,直到我尝试覆盖(扩展)来自article.html.twig的base.html.twig中的样式表块。

I get an error message that this can only be achived if I extend base.html.twig (I know it works like that but its not what I want)

我收到一条错误消息,如果我扩展base.html.twig(我知道它的工作原理是这样,但它不是我想要的),这只能得到实现

I want in fact to attach to article.html.twig the css and the javascript related to the html in this template and that they only get linked (loaded by the browser) in the section of the page whenever I include the template in any other template. It should work like a standalone component (webpart) or whatever this is called.

我希望事实上附加到article.html.twig css和与此模板中的html相关的javascript,并且每当我将模板包含在任何其他模板中时,它们只会在页面的部分中链接(由浏览器加载)模板。它应该像独立组件(webpart)或其他任何组件一样工作。

Do any of you know if such a thing is possible?

你们中的任何人都知道这样的事情是否可能?

Thanks in advance.

提前致谢。

Here is the base.html.twig:

这是base.html.twig:

<!DOCTYPE html>
<head>
    <meta charset="UTF-8" />
    {% block stylesheets %}
    <link rel="stylesheet" type="text/css" media="all" href="{{ asset('style.css') }}" />
    {% endblock %}
</head>
<body>
<p>Test include:</p>
{{ include('article.html.twig') }}
</body>

Here is the article.html.twig

这是article.html.twig

{% block stylesheets %}
{{ parent() }}
<link rel="stylesheet" type="text/css" media="all" href="{{ asset('custom.css') }}" />
{% endblock %}
<div id="article">
     This is an Article!
</div>

1 个解决方案

#1


0  

Sorry, I just read your question again, and now I fully understand what you are trying to achieve.

对不起,我刚刚再次阅读了您的问题,现在我完全理解您要实现的目标。

Unfortunately it is not possible to override a block from within an include. It's exactly like the error message already states... It is only possible to override a block if you extend the original template.

不幸的是,无法从包含中覆盖块。它与错误消息的状态完全相同......如果扩展原始模板,则只能覆盖块。

#1


0  

Sorry, I just read your question again, and now I fully understand what you are trying to achieve.

对不起,我刚刚再次阅读了您的问题,现在我完全理解您要实现的目标。

Unfortunately it is not possible to override a block from within an include. It's exactly like the error message already states... It is only possible to override a block if you extend the original template.

不幸的是,无法从包含中覆盖块。它与错误消息的状态完全相同......如果扩展原始模板,则只能覆盖块。