2011-09-26 101 views
11

我想實現這樣的事情:HTML中的Symfony2表單標籤,而不是純文本

<div> 
    <input type="checkbox" name="checkbox" id="checkbox_id" /> 
    <label for="checkbox_id">I agree to the <a href="/tos">Terms of Service</a></label> 
</div> 

我來實現,這是通過最近的:

<div> 
    {{ form_widget(form.agreeWithTos) }} 
    <label for="{{ form.agreeWithTos.vars.id }}">I agree to the <a href="#">Terms of Service</a></label> 
</div> 

是否有更好的方法?必須指定{{form.agreeWithTos.vars.id}}不雅。 :)

+1

究竟是什麼問題? –

回答

1

我認爲您在尋找form theming。這樣,您就可以在獨立文件中對每一部分表單進行樣式設置,無論如何都是您想要的,然後只需以「優雅」的方式對其進行排序,即可使用{{ form_row(form) }}或僅僅使用{{ form_widget(form) }}。這取決於你如何設置它。

9

用我的形式,主題下面的代碼解決了這個問題:

{# ---- form-theme.html.twig #} 
{% block checkbox_row %} 
{% spaceless %} 
<div> 
    {{ form_errors(form) }} 

    <label class="checkbox" for="{{ form.vars.id }}"> 
     {{ form_widget(form) }} 
     {{ label|default(form_label(form)) | raw }} 
    </label> 
</div> 
{% endspaceless %} 
{% endblock %} 
在表單的模板

然後你可以使用:

{% form_theme form '::form-theme.html.twig' %} 

{{form_row(form.termsOfServiceAccepted, { 
     'label' : 'I have read and agree to the <a href="#">Terms and conditions</a>' 
    }) 
}} 

這種方式,從形式 - 塊主題將應用於頁面上的任何複選框。如果您還需要使用默認的主題,你可以添加一個參數來啓用特殊的渲染:

{# ---- form-theme.html.twig #} 
{% block checkbox_row %} 
{% spaceless %} 
    {% if not useTosStyle %} 
     {{ parent() }} 
    {% else %} 
     {# ... special rendering ... #} 
    {% endif %} 
{% endspaceless %} 
{% endblock %} 

這將是這樣使用:

{% form_theme form '::form-theme.html.twig' %} 

{{form_row(form.termsOfServiceAccepted, { 
     'useTosStyle' : true, 
     'label' : 'I have read and agree to the <a href="#">Terms and conditions</a>' 
    }) 
}} 
0

因此形成主題化是相當複雜的。我發現的最簡單的事情就是壓制字段的標籤(Symfony表單類中的'label'=> false),然後在twig html中添加html標籤。

0

我一直在打我的頭,然後有一個尤里卡時刻。最簡單的方法就是創建一個Twig擴展。

這裏是我的嫩枝代碼:

{# twig example #} 
{% block form_label %} 
    {% set label = parent() %} 
    {{ label|unescape|raw }} 
{% endblock %} 

和PHP:

<?php 
new Twig_SimpleFilter('unescape', function($value) { 
    return html_entity_decode($value); 
}); 

一對夫婦的注意事項:

  • 這取消轉義所有以前逃脫代碼。如果有必要,你肯定應該再次逃脫。
  • 這需要一個extends標籤作爲您自己的自定義表單主題中的目標表單主題,您可以在後續表單中使用該標籤。把樹枝代碼放在一個自定義的表單主題中,並用這個代替其他表單主題/主題的引用。

總的來說,這是我所能找到的最大和最好結果的最少代碼行。它也是超便攜和乾的:你可以擴展任何形式的主題,標籤會改變,而不需要改變代碼的其餘部分。

0

你可以利用的形式主題化的另一種方式:你可以移動<label>標籤form_label()功能。

創建自定義表單的主題,併爲複選框只移動<label>標籤form_label功能外:有效現在

{% block checkbox_row %} 
    <label>{{ form_label(form) }}</label> 
    {{ form_errors(form) }} 
    {{ form_widget(form) }} 
{% endblock checkbox_row %} 

{% block checkbox_label %} 
    {{ label }} 
{% endblock checkbox_label %} 

,在你teplate,超越您的複選框的label,從而注入HTML成標籤功能:

{% form_theme form 'yourtheme.html.twig' _self %} 

{% block _your_TOS_checkbox_label %} 
    I agree with <a href="#" target="_blank">terms and conditions</a> 
{% endblock _your_TOS_checkbox_label %} 
相關問題