最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

symfony - Webpack Encore not loading JavaScript in base template - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked May 9, 2019 at 20:43 AlexAlex 1,1093 gold badges19 silver badges38 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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

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.

发布评论

评论列表(0)

  1. 暂无评论