是否可以覆盖表单帮助程序?

3
使用文档,我可以为围绕字段的布局设置自己的辅助程序,但我也想个性化一些由play提供的字段。
主要原因是为了Twitter Bootstrap 2,在checkbox.scala.html中需要更改。
@input(field, args:_*) { (id, name, value, htmlArgs) =>
    <input type="checkbox" id="@id" name="@name" value="@boxValue" @(if(value == Some(boxValue)) "checked" else "") @toHtmlArgs(htmlArgs.filterKeys(_ == 'value))>
    <span>@args.toMap.get('_text)</span>
}

致:

<label class="checkbox">
    <input type="checkbox" name="@name" id="@id" value="@boxValue" @(if(value == Some(boxValue)) "checked" else "") @toHtmlArgs(htmlArgs.filterKeys(_ == 'value)) />
    @args.toMap.get('_text)
</label>

如何实现这个功能? 感谢您的帮助!
2个回答

8
我最终是这样做的:
我创建了一个名为views.helpers.form的包,其中包含:
bootstrap.scala.html:
@(elements: helper.FieldElements)

<div class="control-group@if(elements.hasErrors) { error}">
    <label class="control-label" for="@elements.id">@elements.label(elements.lang)</label>
    <div class="controls">
        @elements.input
        @elements.infos(elements.lang).map { info =>
            <span class="help-inline">@info</span>
        }
        @elements.errors(elements.lang).map { error =>
            <span class="help-block">@error</span>
        }
    </div>

checkbox.scala.html :

@**
 * Generate an HTML input checkbox.
 *
 * Example:
 * {{{
 * @checkbox(field = myForm("done"))
 * }}}
 *
 * @param field The form field.
 * @param args Set of extra HTML attributes ('''id''' and '''label''' are 2 special arguments).
 * @param handler The field constructor.
 *@
@(field: play.api.data.Field, args: (Symbol,Any)*)(implicit handler: helper.FieldConstructor, lang: play.api.i18n.Lang)

@boxValue = @{ args.toMap.get('value).getOrElse("true") }

@helper.input(field, args:_*) { (id, name, value, htmlArgs) =>
    <label class="checkbox">
        <input type="checkbox" id="@id" name="@name" value="@boxValue" @(if(value == Some(boxValue)) "checked" else "") @toHtmlArgs(htmlArgs.filterKeys(_ == 'value))>
        @args.toMap.get('_text)
    </label>


div>
</div>

在我的模板中,我所需要做的就是:
@import helper.{FieldConstructor, inputText, inputPassword} @** Import the original helpers *@
@import helpers.form.checkbox @** Import my helpers *@
@implicitField = @{ FieldConstructor(helpers.form.bootstrap.f) }

看,就这样!它能正常工作了!


6

如果您只需使用自己需要的代码,那么编写自己的标签并使用它将更简单,而不是使用提供的帮助程序。这将简化与覆盖平台标记相关的潜在问题。


1
是的,你说得对,这是一个不错的方法。我会尝试一下!谢谢! - Cyril N.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接