您可以創建這樣一個標籤庫...
// grails-app/taglib/com/demo/ParsingTagLib.groovy
package com.demo
class ParsingTagLib {
static defaultEncodeAs = 'html'
static namespace = 'parsing'
def retrieveContentsOfTag = { attrs ->
// The regex handling here is very
// crude and intentionally simplified.
// The question isn't about regex so
// this isn't the interesting part.
def matcher = attrs.stringToParse =~ /<(\w*)>/
out << matcher[0][1]
}
}
您可以調用該標籤從GSP像這樣的東西填充的文本字段的值....
<g:textField name="firstName" value="${parsing.retrieveContentsOfTag(stringToParse: firstName)}"/>
<g:textField name="lastName" value="${parsing.retrieveContentsOfTag(stringToParse: lastName)}"/>
如果從這樣的控制器渲染...
// grails-app/controllers/com/demo/DemoController.groovy
package com.demo
class DemoController {
def index() {
// these values wouldn't have to be hardcoded here of course...
[firstName: '<Jeff>', lastName: '<Brown>']
}
}
這將導致HTML,看起來像THI s ...
<input type="text" name="firstName" value="Jeff" id="firstName" />
<input type="text" name="lastName" value="Brown" id="lastName" />
我希望有幫助。
UPDATE:
取決於你真正想要做的,你也可以看看像這樣的東西包裹整個文本字段一代的事情你的標籤內...
// grails-app/taglib/com/demo/ParsingTagLib.groovy
package com.demo
class ParsingTagLib {
static namespace = 'parsing'
def mySpecialTextField = { attrs ->
// The regex handling here is very
// crude and intentionally simplified.
// The question isn't about regex so
// this isn't the interesting part.
def matcher = attrs.stringToParse =~ /<(\w*)>/
def value = matcher[0][1]
out << g.textField(name: attrs.name, value: value)
}
}
那麼你的GSP代碼看起來是這樣的......
<parsing:mySpecialTextField name="firstName" stringToParse="${firstName}"/>
<parsing:mySpecialTextField name="lastName" stringToParse="${lastName}"/>
是什麼需要返回?爲什麼要收集'Matches',我相信你不需要'Matches',而只需要'String's? 無論如何,只需將您的域類的實例作爲模型部件傳遞並從GSP中調用即可。究竟如何 - 取決於您在文本框中需要做什麼,GSP代碼示例會有所幫助。 – 2011-05-15 15:51:14