我正在尝试在 Symfony 3.3.2 ( https://symfony.com/doc/2.8/form/form_customization.html ) 中自定义我的表单渲染。
app/Resources/views/form/fields.html.twig
{% block test %}
<p>TEST</p>
{% endblock %}
app/Resources/views/default/new.html.twig
{% form_theme form 'form/fields.html.twig' %}
{{ form_widget(form.age) }}
{{ block('test') }}
src/AppBundle/Controller/DefaultController.php
class DefaultController extends Controller
{
public function indexAction(Request $request)
{
$test = new Test();
$test->setAge(8);
$form = $this->createForm(TestType::class, $test);
return $this->render('default/new.html.twig', array(
'form' => $form->createView(),
));
}
}
src/AppBundle/Entity/Test.php
namespace AppBundle\Entity;
class Test
{
protected $age;
public function getAge()
{
return $this->age;
}
public function setAge($age)
{
$this->age = $age;
}
}
src/AppBundle/Form/TestType.php
class TestType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('age')
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Test::class,
));
}
}
应用程序/配置/config.yml
twig:
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
form_themes:
- 'form/fields.html.twig'
我想比我误解了一些东西,因为我希望看到一个带有 8 个数字并且在字符串“TEXT”下方的输入,但是实际上,我只有输入。那么如何在 new.html.twig 中插入自定义块呢?
form_theme
不是包含其他块的方法,它只是具有一些约定的样式。如果您需要为表单赋予样式,那么您只需使用主题和form_widget
. 如果您需要包含一些其他块,请创建该块(在单独的文件中,甚至在同一文件中)并在embed
和include
指令之间进行选择。对于embed
和include
我之间的区别,我建议阅读这个 SO 答案
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句