我有一个看起来像这样的布局:
<html>
<body>
<!-- Omitted -->
<div class="content">
{% block body %}{% endblock %}
</div>
<script src="js/vendor.js"></script>
{% block javascripts %}
<!-- I want to be able to inject inline scripts from sub-templates here -->
{% endblock %}
</body>
</html>
然后我从 FOSUserBundle 覆盖了 register_content.html.twig 模板,在其中我尝试将脚本注入到"javascripts"块中,如下所示:
{% block javascripts %}
<script>
// Some inline JS
</script>
{% endblock %}
我遇到的问题是内联脚本似乎被注入在"正文"块的末尾,而不是在"脚本"块中。
这是我得到的输出:
<!-- This should be below js/vendor.js scripts -->
<script>
// Some inline JS
</script>
</div>
</div>
<script src="js/vendor.js"></script>
我做错了什么?我的问题是否在于 FOSUserBundle 以及它继承的自己的模板(它仍然使用我的布局和我在其中的所有内容;而不是它自己的布局)。我在这里很困惑。
附言我是Symfony/Twig的新手,所以请对我放轻松。
编辑:这些是我覆盖的FOSUserBundle布局和模板:
app/Resources/FOSUserBundle/views/layout.html.twig:
{% extends 'AcmeWebBundle::layout.html.twig' %}
{% block title %}Acme Demo Application{% endblock %}
{% block body %}
{% block fos_user_content %}{% endblock %}
{% endblock %}
{% block javascripts %}
{{ parent() }}
{% endblock %}
app/Resources/FOSUserBundle/views/Registration/register.html.twig:
{% extends "FOSUserBundle::layout.html.twig" %}
{% block body %}
{% block fos_user_content %}
{% include "FOSUserBundle:Registration:register_content.html.twig" %}
{% endblock fos_user_content %}
{% endblock %}
{% block javascripts %}
{% parent() %}
{% endblock %}
app/Resources/FOSUserBundle/views/Registration/register_content.html.twig:
<div class="page-header">
<h2>Register</h2>
</div>
<form action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST" class="fos_user_registration_register form-horizontal">
<!-- HTML Omitted -->
</form>
{% block javascripts %}
{% javascripts '@AcmeWebBundle/Resources/public/js/app.js' %}
<script>
// jQuery is undefined because it gets defined below the 'javascripts' block in the parent layout
console.dir(window.jQuery);
</script>
{% endjavascripts %}
{% endblock %}
编辑后情况更加清晰。
您期望的行为仅适用于模板继承; 它不适用于include
,就像您在app/Resources/FOSUserBundle/views/Registration/register.html.twig
中拥有它的方式一样。
要执行所需的操作,请执行下列操作之一:
-
将
javascript
块app/Resources/FOSUserBundle/views/Registration/register_content.html.twig
中的内联 JavaScript 代码放在javascript
块app/Resources/FOSUserBundle/views/Registration/register.html.twig
内 -
让模板
app/Resources/FOSUserBundle/views/Registration/register.html.twig
从app/Resources/FOSUserBundle/views/Registration/register_content.html.twig
继承并根据需要覆盖其块(register_content.html.twig
不会扩展layout.html.twig
,所以这没有多大意义)