【问题标题】:Is it possible to override form helpers?是否可以覆盖表单助手?
【发布时间】:2012-04-18 09:52:45
【问题描述】:

使用文档,我可以为我的领域的布局设置自己的助手,但我还想个性化一些由 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>

我该怎么做? 感谢您的帮助!

【问题讨论】:

    标签: templates scala playframework-2.0


    【解决方案1】:

    我终于做到了:

    我创建了一个包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) }
    

    然后瞧!有效!

    【讨论】:

      【解决方案2】:

      使用您想要的代码编写您自己的标签并使用它而不是提供的帮助程序会更简单。它将简化与覆盖平台标签相关的潜在问题。

      【讨论】:

      • 是的,你是对的,这是一个好方法。我会试试看!谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多