简体   繁体   English

Webpack Encore未在基本模板中加载JavaScript

[英]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 : 我在Symfony 4项目中使用了Webpack Encore,并且在base.html.twig包含了JavaScript的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. 但是,当我的模板之一( index.html.twig )中包含完全相同的Twig帮助器时,JavaScript不会加载。

So my question is, why does the above Twig helper work in one of my templates, but not in my base template? 所以我的问题是,为什么上面的Twig helper可以在我的模板之一中工作,而不在我的基本模板中工作?

It's failing because it's inside your javascript block. 失败了,因为它在您的javascript块内。

Your template extends base.html.twig , so whatever you place within your javascript block in any template will be inside the javascript block. 您的模板扩展了base.html.twig ,因此无论您在任何模板的javascript块中放置的内容如何,​​都将在javascript块内。

But if you do the same within base.html.twig it will just be ignored. 但是,如果您在base.html.twig执行相同的操作,它将被忽略。

Just move {{ encore_entry_script_tags('app') }} out of your javascript block. 只需将{{ encore_entry_script_tags('app') }}从您的JavaScript块中移出即可。

base.html.twig 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. 请记住以下base.html.twig :如果它位于您的布局(即base.html.twig ,则请勿在{% block %}标记内放置任何内容。 It will just be ignored. 它将被忽略。

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 但是,还有另一种解决方案,不仅仅是将代码移到基本模板的块之外,而是调用parent()函数

main.twig main.twig

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

base.twig base.twig

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

output 产量

Foo
Bar 酒吧

demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM