6

I need include a twig file with a block, but this file will be added in differents places. The file is this:

HTML CODE BLABLA

{% block javascript %}
    <script>
        Code associated with the html
    </script>
{% endblock %}

With include, is inserted all but not respect order block. Also I can load template with "use" but I havent access to the vars :S

{% include 'file.html.twig' %} No respect block
{% use 'file.html.twig' %} cant access vars

How can I do it ?. (Sorry for my english)

2 Answers 2

3

To override a block you have to use the extends function. Your template may extends the parent, so the javascript block from the sub-template will replace the one from the parent.

You cannot mix include and extend.

Sign up to request clarification or add additional context in comments.

2 Comments

I dont know why I cannot mix them. This file will be included in differents pages because is a little "widget" for this reason I cant use extends. I think this problem should be very common :S.
You just have to write your javascript code outside of any block in your included template. It's true that it won't be at a particular place in your layout but it will work.
1

Have you tried the embed tag?

The embed tag combines the behaviour of include and extends. It allows you to include another template's contents, just like include does. But it also allows you to override any block defined inside the included template, like when extending a template.

2 Comments

this is quite the opposite, what OP wants is to be able to include, and that within included file would be able to override block that is in parent
I expect that's why OP already accepted the other answer. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.