[英]How to avoid groovy code in GSP?
我必須基於多於4行的Groovy代碼的某些邏輯來顯示是否選中復選框...我不喜歡在GSP頁面中編寫它。是否有任何taglib或某種方式可以提取邏輯超出GSP頁面。 在這里我可以訪問模型對象並請求對象。
TagLib是放置邏輯的好地方,您可以將需要的內容作為屬性傳遞並進行測試:
class MyTagLib {
static namespace = "my"
def somecheckbox= { attrs ->
def model = attrs.remove('model')
if() { //tests goes here
//you can also test if you need to mark the checkbox as checked
if() {
attrs.checked = "checked"
}
out << g.checkbox(attrs: attrs) //remaining attrs will be applied to the checkbox
}
}
}
myview.gsp
<my:somecheckbox model="${model}" name="checkboxname" value="${checkboxValue}" />
您至少有3個選項:
模型屬性
如果僅對單個頁面或單個控制器執行復雜的邏輯,請在controller方法中執行邏輯,然后通過布爾將布爾結果傳遞給視圖:
// in your controller
def myAction() {
[shouldDrawCheckbox: shouldDrawCheckBox(...)]
}
private boolean shouldDrawCheckBox(/* info for decision making */) {
// decision making
}
服務方式
如果要從多個控制器訪問相同的邏輯,則可以將shouldDrawCheckBox
方法提取到服務中,然后再次將結果傳遞給模型。
class MyController {
def myService
def myAction() {
[shouldDrawCheckbox: myService.shouldDrawCheckbox(...)]
}
}
class MyService {
boolean shouldDrawCheckBox(...) {
// logic!
}
}
自定義Taglib
如果要避免通過模型傳遞決策,或者如果邏輯更通用,則可以創建自定義標記庫。
class MyTaglib {
static namespace = "my"
def myCheckbox = { attrs ->
// extract decision info from the attrs
// perform logic with info
if (shouldDrawCheckbox)
out << g.checkbox(attrs: attrs)
}
}
}
您認為:
<my:myCheckbox whateverYourAttribsAre="value" name="..." value="..."/>
理想情況下,邏輯應該傳遞給控制器,控制器renders
gsp並在model
對象中設置標志。 如果gsp是模板的子級,則該標志必須通過。 當我們在grails中有合適的綁定框架時,視圖層中的DOM操作並不理想。
使用g:
名稱空間。 http://grails.org/doc/2.2.x/ref/Tags/checkBox.html
<g:checkBox name="myCheckbox" value="${condition}" />
沒有比這更簡單的了。 所有邏輯都應在控制器內部完成。
您在頁面上需要的所有數據都可以由控制器傳遞。 只需返回一個Map
。
class MyController {
def index() {
def someCondition = true
[request:request, condition:someCondition]
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.