Alex
Alex

Reputation: 1109

Webpack Encore not loading JavaScript in base template

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?

Upvotes: 1

Views: 1886

Answers (2)

Preciel
Preciel

Reputation: 2837

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.

Upvotes: 4

DarkBee
DarkBee

Reputation: 15625

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

Upvotes: 5

Related Questions