official documentation on how to create a custom field建议在应用程序配置(app/config/config.yml
)中添加以下行以注册其他模板:
twig:
form:
resources:
- 'AcmeDemoBundle:Form:fields.html.twig'
是否有另一种方法可以通过将模板加载到bundle的依赖注入代码中来将模板添加到twig表单资源中?任何代码示例都将不胜感激。
答案 0 :(得分:2)
如果您查看TwigExtension(在TwigBundle内),您会看到配置存储在twig.form.resources
参数中:
$container->setParameter('twig.form.resources', $config['form']['resources']);
您的包可以在编译器传递中向此参数添加元素。在加载所有bundle扩展并且容器具有一组完整的服务之后执行编译器传递。在Symfony documentation中了解有关如何创建编译器传递的更多信息。
基本上,想要做的事情就像:
$resources = [];
if ($container->hasParameter('twig.form.resources')) {
$resources = $container->getParameter('twig.form.resources');
}
$resources[] = 'your_awesome_template_resource.twig';
$container->setParameter('twig.form.resources', $resources);
答案 1 :(得分:-1)
我想做同样的事情,我想从bundle加载表单模板而不向config.yml添加任何东西。以下是它的完成方式:
您需要在您的PrependExtensionInterface
bundle folder/DependencyInjection/BundleNameExtension.php
像这样:
class YourExtension extends Extension implements PrependExtensionInterface {
...
public function prepend(ContainerBuilder $container) {
foreach (array_keys($container->getExtensions()) as $name) {
switch ($name) {
case 'twig':
$container->prependExtensionConfig(
$name,
array('form' => array('resources' => array('YourExtension:Form:fields.html.twig')))
);
break;
}
}
}
}
以下是SummerNote套装的完整示例: https://github.com/solilokiam/SummernoteBundle/blob/a510386c49144ff0f4391c460bcc1640fd26b691/DependencyInjection/SolilokiamSummernoteExtension.php