1

I am using a Webpack Encore in my Symfony 4 project, and when including the Twig helper for JavaScript in my base.html.twig:

{% block javascripts %}
    {{ encore_entry_script_tags('app') }}
{% endblock %}

The JavaScript doesn't load, however, when including the exact same Twig helper in one of my templates (index.html.twig), the JavaScript loads in.

So my question is, why does the above Twig helper work in one of my templates, but not in my base template?

2 Answers 2

5

What preciel said is true, using a block inside a template that extends another template will overwrite the default code inside that said block.

However there is another solution than just moving the code outside the block in the base template and that's calling the parent() function

main.twig

{% extends 'base.twig' %}
{% block foo %}
    {{ parent() }}
    Bar
{% endblock %}

base.twig

{% block foo  %}
    Foo
{% endblock %}

output

Foo
Bar

demo

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

3 Comments

Good to know, though I find it more "complex" and prone to make mistakes. But still, good to know. Can prove useful in some cases I bet.
Have to disagree about it being more complex. If you have a block that is designated for page javascript, only there is core javascript in the template that you require as well, using parent() is a great way to keep everything in place with the same basic structure. This is extremely useful in my experience and certainly results in a cleaner markup. Why would you want 2 javascript blocks when you can have one?
Didn't knew abou it. Might prove useful indeed.
4

It's failing because it's inside your javascript block.

Your template extends base.html.twig, so whatever you place within your javascript block in any template will be inside the javascript block.

But if you do the same within base.html.twig it will just be ignored.

Just move {{ encore_entry_script_tags('app') }} out of your javascript block.

base.html.twig

{{ encore_entry_script_tags('app') }}
{% block javascripts %}
    {# nothing here, your templates will overwrite it when  you extends base.html.twig #}
{% endblock %}

Remember this: If it's inside your layout, which is base.html.twig, then don't place anything inside the {% block %} tags. It will just be ignored.

Comments

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.