简体   繁体   English

Symfony 2 Form主题和JS

[英]Symfony 2 Form theming and JS

I have AFormType class and corresponding twig template which is processed in some_controller_action.html.twig such way: 我有AFormType类和相应的树枝模板,该模板在some_controller_action.html.twig中进行了以下处理:

{% form_theme a_form with ['ABundle:Form:a-form.html.twig'] %}
{{ form(a_form) }}

I want a-form.html.twig contain javascript, which is related to the form only, and to nothing else. 我希望a-form.html.twig包含javascript,该javascript仅与表单有关,而与其他无关。 So I added there following: 所以我在这里添加了以下内容:

{% block javascripts %}
<script type="text/javascript">
    $(document).ready(function () {
    ...
    }
{% endblock %}

some_controller_action.html.twig also has block javascripts, which contains document.load. some_controller_action.html.twig也有块javascript,其中包含document.load。

The problem: template engine ignores a_form.html.twig script and not includes to rendered page. 问题:模板引擎会忽略a_form.html.twig脚本,并且不包含在呈现的页面中。 controller's html.twig JS is processed correctly. 控制器的html.twig JS已正确处理。

How may I solve the issue? 我该如何解决这个问题?

The problem you are seeing is because The Symfony twig form extension handles the loading and rendering of blocks in theme files. 您看到的问题是因为Symfony树枝状表单扩展名可以处理主题文件中块的加载和渲染。 You cannot add anything other than form widgets to your themes. 您不能在主题中添加除表单小部件以外的任何内容。

You can try importing your theme file and setting your current file as a theme. 您可以尝试导入主题文件并将当前文件设置为主题。 But you may still have to call block('javascripts') 但是您可能仍然需要调用block('javascripts')

{% form_theme a_form _self %}
{% use 'ABundle:Form:a-form.html.twig' %}

The only other way to add javascript for a form controller is to add it directly to the HTML in the widget. 为表单控制器添加JavaScript的唯一其他方法是将其直接添加到小部件中的HTML。 Gregwar CaptchaBundle does this. Gregwar CaptchaBundle执行此操作。 The problem with this approach is that the script will be added each time a form controller is rendered. 这种方法的问题在于,每次呈现表单控制器时都会添加脚本。

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

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