在GSP

2011-05-15 60 views
1

調用域方法我創建了我的領域類的方法叫做affichage(s)可以檢索<name><adresse>之間類似的字符串:在GSP

enter code here 



def affichage(s){ 

def l=[] 
def regex = /\<.\w*.\>/ 
def matcher = s =~ regex 
matcher.each{match -> 
l.add(match)} 
l.each{ 
for (i in l){ 
println i 
}}}} 

我已經運行在groovyConsole中這個功能,它的確定。

如何在gsp中調用此方法將其應用於文本字段?

+0

是什麼需要返回?爲什麼要收集'Matches',我相信你不需要'Matches',而只需要'String's? 無論如何,只需將您的域類的實例作爲模型部件傳遞並從GSP中調用即可。究竟如何 - 取決於您在文本框中需要做什麼,GSP代碼示例會有所幫助。 – 2011-05-15 15:51:14

回答

5

要做到這一點grails的方式,你會加載域控制器中的對象,然後將其傳遞給視圖。因此,像在控制器中的以下內容:

// assuming theDomainObject/anotherObject are loaded, preferably via service calls 
render view: 'theView', model: [object: theDomainObject, another: anotherObject] 

,然後在視圖中,你可以做的第一要調用的方法

${object.yourMethod()} 

${another.someprop} 

注意到,在未來你得到一個屬性。還要注意,在大括號內,您可以引用您在控制器中傳回的模型中的內容。

${...} 

告訴gsp使用傳回的模型對象。 grails很酷。

0

使上一個答案清晰。

您不通過域本身。您將模型的實例作爲:

render(view: 'theView', model: [object: new MyDomain(), another: new YourDomain()] 

其中MyDomain和YourDomain是Grails中的域類。

0

您可以創建這樣一個標籤庫...

// 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}"/>