我想在Symfony中自定义表单渲染。我检查了文档,发现可以使用{{form_theme}}
标记设置渲染主题。如果一次只有一个表单,这是完美的,但是如果在同一个模板中有多个表单,这就不起作用了。
我index.html.twig的一个简单例子
{% extends 'base.html.twig' %}
{% block body %}
<h1>Hello Form 1</h1>
{% form_theme form1 'bootstrap_3_layout.html.twig' %}
{{ form_start( form1 ) }}
{{ form_end( form1 ) }}
<h1>Hello Form 2</h1>
{% form_theme form2 'bootstrap_3_horizontal_layout.html.twig' %}
{{ form_start( form2 ) }}
{{ form_end( form2 ) }}
{% endblock %}
正如您所看到的,有两个表单变量,我希望form1
使用的bootstrap\u 3\u布局来呈现。html。细枝“
和形成2
,具有'bootstrap\u 3\u水平布局。html。细枝“
。我不知道细枝的内部结构,但我认为主题覆盖了它们的块定义。
结果是这样的
因此,我的问题是,我如何能够在不相互干扰的情况下呈现具有给定主题的形式。有没有办法在单独的干净细枝过程中渲染窗体?
我尝试了树枝扩展与自定义函数,但似乎该函数使用相同的Twig_Environment。我还尝试了一个子请求,但它也不起作用。
如果您只想对表单使用水平
类,您可以将其添加到form_start()
:
{% extends 'base.html.twig' %}
{% block body %}
<h1>Hello Form 1</h1>
{% form_theme form1 'bootstrap_3_layout.html.twig' %}
{{ form_start( form1 ) }}
{{ form_end( form1 ) }}
<h1>Hello Form 2</h1>
{% form_theme form2 'bootstrap_3_horizontal_layout.html.twig' %}
{{ form_start(form2, {'class': 'horizontal', 'attr': {'class': 'horizontal'}}) }}
{{ form_end( form2 ) }}
{% endblock %}
感谢艾哈迈德·苏瓦尼的回答。
我建议您将每个细枝标记{{form()}}
封装在
/* display the <label> in div.form_1 as red */
div.form_1 label {
color: Red;
}
/* Email field in div.form_2 will only have a width of 50% */
div.form_2 input[type=email] {
width: 50%;
}
/* Password field in div.form_2 will have a left margin and will be narrower */
div.form_2 input[type=password] {
margin-left: 5em;
width: 30%;
}
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="well">
<h2>Default form</h2>
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
</form>
</div>
<div class="form_1 well">
<h2>Form 1</h2>
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
</form>
</div>
<div class="form_2 well">
<h2>Form 2</h2>
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
</form>
</div>
您的代码在我的测试中运行良好。
您可能正在发送导致问题的form1和form2的相同表单类型。如果您发送两种不同的表单类型,它应该可以工作。