带有 Laravel 的标签内的单选和复选框

Posted

技术标签:

【中文标题】带有 Laravel 的标签内的单选和复选框【英文标题】:Radio and checkbox inside label with Laravel 【发布时间】:2014-08-13 05:05:24 【问题描述】:

有没有办法使用Form::label 与复选框和单选输入来生成bootstrap 建议的标记?目的是在标签内添加输入字段,而不是使用ids 附加它们。我想避免对Form::radio周围的标记进行硬编码

<div class="checkbox">
  <label>
    <input type="checkbox" value="">
    Option one is this and that&mdash;be sure to include why it's great
  </label>
</div>

<div class="radio">
  <label>
    <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
    Option one is this and that&mdash;be sure to include why it's great
  </label>
</div>
<div class="radio">
  <label>
    <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
    Option two can be something else and selecting it will deselect option one
  </label>
</div>

【问题讨论】:

您需要扩展Form 类并编写您的自定义input 实现。幸运的是捆绑实现已经存在:bundles.laravel.com/search/tag/Bootstrap (bootsparks, bootstrapper) 我试图弄清楚如何扩展 Form 类。结果我宁愿选择&lt;label&gt; Form::radio(...) Radio Label&lt;/label&gt; :D 【参考方案1】:

您可以编写自己的表单宏并使用它来构建您喜欢的 html

http://laravel.com/docs/4.2/html#custom-macros

类似:

Form::macro('bootCheckbox', function($value, $label)

 $html = '<div class="checkbox"><label><input type="checkbox" value="';
 $html .= $value;
 $html .= '">';
 $html .= $label;
 $html .= '</label></div>'
 return $html

然后你可以在你的视图中这样称呼它:

Form::bootCheck('i_dont_know_what_value_youd_like', 'Option one is this and that&amp;mdash;be sure to include why it's great')

当然,您可以将任何您喜欢的值传递给宏并构建您想要的任何东西(假设您在宏端的代码是合理的)。 上面的例子应该像你显示的那样输出一个复选框,但它不是太干净,我没有测试过。

至于代码放在哪里,你可以把它放在任何地方,只要你链接它。我的表单宏(更广泛)存在于 /app/start/form_macros.php 中,并在 /app/start/global.php 中需要,只需在其末尾添加 require dirname(__FILE__) . '/form_macros.php';

【讨论】:

【参考方案2】:

感谢 Saint Genius 的回答,让我朝着正确的方向前进。 +1

但是,他缺少几个分号,没有在复选框字段中包含 name 属性,并且将 $html 字符串分成几行,使其难以阅读。

我已经改写了一下:

Form::macro('labelCheckbox', function($name, $value, $label)

    $html = "<label>
                <input name='$name' type='checkbox' value='$value' /> $label
            </label>";

    return $html;
);

然后在视图中:

 Form::labelCheckbox('fruits', 'apple', 'Apple') 

【讨论】:

True dat,在我脑海中打出来的。但是我认为您有点吹毛求疵,我确实在回答中声明代码未经测试且不干净。任何假人都应该能够修复它xD 是的,不打算编辑它。它不是用于复制/粘贴,仅用于示例目的。

以上是关于带有 Laravel 的标签内的单选和复选框的主要内容,如果未能解决你的问题,请参考以下文章

用jquery修改默认的单选框radio或者复选框checkbox选择框样式

android ListView GridView 单选和复选列子

js单选和全选

js实现元素的多选,或单选功能

如何在wxPython 4.0.3中指定单选框内的单选按钮的大小

表单中的单选/复选框“必需”属性?