我正在为节目明星评级创建一个自定义表单类型,(基本五个单选按钮)。我为渲染创建了一个自定义块:
{% block star_rating_widget %}
{% spaceless %}
<div {{ block('widget_container_attributes') }}>
{% for child in form %}
{{ form_widget(child) }}
{% endfor %}
</div>
{% endspaceless %}
{% endblock %}
此块使用默认的radio_widget块渲染五个单选按钮。
{% block radio_widget %}
{% spaceless %}
<input type="radio" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
{% endspaceless %}
{% endblock radio_widget %}
我需要知道如何覆盖radio_widget块以添加一些类和属性,但仅限于在star_rating_block内渲染时。
答案 0 :(得分:4)
可能的解决方案:
{% block radio_widget %}
{% if "custom_widget" in form.parent.vars.block_prefixes %}
// custom view
{% else %}
// default view from form_div_layout.html.twig
{% endif %}
{% endblock radio_widget %}
答案 1 :(得分:2)
您可以通过第二个参数将变量传递给form_widget
。您基本上允许自定义类型中的一组选项,并通过树枝函数传递它们。
{{ form_widget(child, {attr: {class: classNameVar}}) }} {# passing some classes through the variable classNameVar
您可以在the documentation about twig template form function and variable reference中找到更多信息。
在同一文档中,您可以找到有关不同form variables的信息。