简体   繁体   English

如何使用 Twig 在 Symfony2 中渲染标签内的输入

[英]How to render input inside label in Symfony2 with Twig

I try to create a custom form theme for my project where I want to render all checkbox fields INSIDE the label like:我尝试为我的项目创建一个自定义表单主题,我想在其中呈现标签内的所有复选框字段,例如:

<label><input type="checkbox" /><label>

I've found out that I have to change the choice_widget_expanded block for this:我发现我必须为此更改 choice_widget_expanded 块:

{% block choice_widget_expanded %}
    {% spaceless %}
        <div {{ block('widget_container_attributes') }}>
        {% for child in form %}
            {{ form_widget(child) }}
            {{ form_label(child) }}
        {% endfor %}
        </div>
    {% endspaceless %}
{% endblock choice_widget_expanded %}

The problem is, when I copy the content of the form_label block into the container instead of calling form_label(child), I don't really see how the block accesses the variable passed(which was child when I called the function), and how to call the form_widget function in the form_label block:问题是,当我将 form_label 块的内容复制到容器中而不是调用 form_label(child) 时,我真的没有看到该块如何访问传递的变量(当我调用函数时它是 child),以及如何在 form_label 块中调用 form_widget 函数:

{% block form_label %}
    <label>{{ form_widget(?? what to put here??) }}</label>
{% endblock form_label %}

Also, if I create a block with a different name, like "form_label_extra" and try to call it, it throws an error, because it's not a registered twig function.此外,如果我创建一个具有不同名称的块,例如“form_label_extra”并尝试调用它,则会引发错误,因为它不是已注册的树枝函数。

Does anyone know how this variables are passed between the form blocks, and how to achieve my goal?有谁知道这个变量是如何在表单块之间传递的,以及如何实现我的目标?

I did the same modifying the following block我做了同样的修改以下块

{% block checkbox_widget %}
{% spaceless %}
<label class="button i_clear"> 
    <input type="checkbox"
        {{ block('widget_attributes') }}
        {% if value is defined %} value="{{ value }}"{% endif %}
        {% if checked %} checked="checked"{% endif %} />
    <span>{{ label }}</span>
</label>
{% endspaceless %}
{% endblock checkbox_widget %}

You will still need to remove the original label, you can modify it with javascript, hide it with css or modify the template so it renders conditionally, whatever is best for you.您仍然需要删除原始标签,您可以使用 javascript 修改它,使用 css 隐藏它或修改模板,以便它有条件地呈现,无论哪种方式最适合您。

This question might also help: Symfony2 - How to put label and input for checkboxes/radios in a same line?这个问题也可能有帮助: Symfony2 - How to put label and input for checkboxes/radios in a同一行?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM