4
votes

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

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.

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)

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.

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

Thanks in advance.

Here is the 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

{% 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
Can you post your base and your article twigs? - Pipe
Have you tried to add a new block inside the javascripts block of base.html.twig? - Oscar Pérez
I have uploaded the necessary code parts to the post. - Noooooob
You are including the article.html.twig into base.html.twig why not just style it in your normal stylesheet from base.html.twig? Also, I think you may want to do the include a little different. Here are the docs: twig.sensiolabs.org/doc/tags/include.html. - nerdlyist
Sure I can style it in base.html.twig but i want to keep javascript stylesheet and html together a a unit. I want my stylesheet and javascript only be loaded on the pages where I include the articles, the best would be with something like the php function require_once so they will be linked/loaded only once I also want to keep them together because they act as a single unit and I would like to use them with the include as a plugin component. I only ask if twig is capable of such a thing cause i thouth about it this was and couldn't implement it. - Noooooob

1 Answers

0
votes

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.