我不得不寫,需要JavaScript的一個自包含表單控件,我是能夠實現你正在試圖通過event_dispatcher
監聽的kernel.response
做的JavaScript在Symfony\Component\HttpFoundation\Response
的末尾添加。這是我的表單類型的一個片段:
<?php
namespace AcmeBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
class AcmeFileType extends AbstractType{
private $twig;
private $dispatcher;
public function __construct(\Twig_Environment $twig, EventDispatcherInterface $dispatcher){
$this->twig = $twig;
$this->dispatcher = $dispatcher;
}
public function buildView(FormView $view, FormInterface $form, array $options){
$javascriptContent = $this->twig->render('AcmeBundle:Form:AcmeFileType.js.twig', array());
$this->dispatcher->addListener('kernel.response', function($event) use ($javascriptContent) {
$response = $event->getResponse();
$content = $response->getContent();
// finding position of </body> tag to add content before the end of the tag
$pos = strripos($content, '</body>');
$content = substr($content, 0, $pos).$javascriptContent.substr($content, $pos);
$response->setContent($content);
$event->setResponse($response);
});
}
...
當您在services.yml定義表單類型,它看起來像這樣:
acme.form.acme_file_type:
class: AcmeBundle\Form\AcmeFileType
arguments:
- @twig
- @event_dispatcher
tags:
- { name: form.type, alias: acmefile }
所以,現在,每次你建立一個形式acmefile
的JavaScript將被追加到<body>
。雖然這個解決方案並不妨礙的javascript從多次出現,但您應該很容易就能夠改善這一點以適應您的需求。
如果您願意,也可以使用$response
對象來改變標頭。
爲什麼你不想修改基本模板?這*是設置你想要導入哪個js \ css文件的地方 – tamir 2012-04-06 21:19:17
我想創建一些自包含表單控件擴展包,並且在AppKernel.php中只啓用一次這個包。此外,如果小部件在當前頁面中沒有用處,我不想包含js/css。 – 2012-04-13 08:18:07
這似乎是Symfony中的一個缺失功能(直到現在)。也許我們應該從[django widget媒體](https://docs.djangoproject.com/en/dev/topics/forms/media/#assets-as-a-static-definition)啓發,它只包含小部件禮物 – 2015-11-28 06:51:19