Skip to content

Instantly share code, notes, and snippets.

@bmc
Created May 3, 2013 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmc/5509913 to your computer and use it in GitHub Desktop.
Save bmc/5509913 to your computer and use it in GitHub Desktop.
Version of Play's @select helper that handles 'data args. Assumes the existence of a LocalHelpers module that contains a deCamelCase function (shown below)
@** Generate a jQuery-friendly <select>. This helper works the same way
* the regular @select helper works, except that any args starting with 'data
* are de-Camel-cased and converted to jQuery-style "data-" attributes. For
* instance, 'dataFooBar becomes "data-foo-bar".
*
* This form helper is basically just a reimplementation of the stock
* @select helper, with additional logic for "data-" attributes.
*@
@(field: play.api.data.Field, options: Seq[(String,String)], args: (Symbol,Any)*)(implicit handler: views.html.helper.FieldConstructor, lang: play.api.i18n.Lang)
@import helper.input
@import views.LocalHelpers._
@import play.api.templates.PlayMagic
@input(field, args: _*) { (id, name, value, htmlArgs) =>
<select id="@id" name="@name"
@defining(htmlArgs.groupBy(a => a._1.toString.startsWith("'data"))) { m =>
@m.get(true).map { dataArgs =>
@for(a <- dataArgs; s = symbolToString(a._1)) {
@(deCamelCase(s) + "=" + a._2)
}
}
@m.get(false).map { otherArgs =>
@PlayMagic.toHtmlArgs(otherArgs)
}
}
>
@args.toMap.get('_default).map { defaultValue =>
<option class="blank" value="">@defaultValue</option>
}
@options.map { v =>
<option value="@v._1" @(if(value == Some(v._1)) "selected" else "")>
@v._2
</option>
}
</select>
}
package views
object LocalHelpers {
/** Default target for offsite anchors.
*/
val OffSiteAnchorTarget = "link"
/** Convert a symbol to a string, for use in HTML.
*/
def symbolToString(sym: Symbol) = sym.toString.substring(1)
/** De-Camel-case a symbol, producing an attribute string.
* Example:
*
* {{{
* deCamelCase('dataFooBar) // produces "data-foo-bar"
* }}}
*/
def deCamelCase(sym: Symbol): String = deCamelCase(symbolToString(sym))
/** De-Camel-case a string, producing an attribute string.
* Example:
*
* {{{
* deCamelCase("dataFooBar") // produces "data-foo-bar"
* }}}
*/
def deCamelCase(s: String): String = {
s.toList.map { c => if (c.isUpper) s"-${c.toLower}" else c }.mkString("")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment