2011-06-22 95 views
0

如何在Grails中從GSP訪問類的字段?例如,以下內容:從Grails中的GSP訪問類字段

geocoder.geocode({ 
     'address': 'london' 
    }, 

我需要在被用戶插入後以編程方式獲取地址。如下所示:

geocoder.geocode({ 
     'address': ${search.city} 
    }, 

其中搜索是類和城市是字段。 有沒有辦法做到這一點? 由於

UPDATE

我嘗試這樣做: 在控制器:

def map = { 
    def searchInstance = Search.get(1) 
    [locationList : Location.list(), search:searchInstance] 
} 

在視圖:

function initialize() { 
    var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 
     'address': ${search.city} 
    }, 
    function(results, status) { 
     if(status == google.maps.GeocoderStatus.OK) { 

      var myMapOptions = { 
        zoom: 8, 
        center: results[0].geometry.location, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
       }; 

       map = new google.maps.Map(document.getElementById("map_canvas"), 
        myMapOptions); 

       <g:each in="${locationList}" status="i" var="location">  
       var point${location.id} = new google.maps.LatLng(${location.lat}, ${location.lng}); 
       var myMarkerOptions${location.id} = { 
         position: point${location.id}, 
         map: map 
        }; 
       if(map.getCenter().distanceFrom(point${location.id}) < 500000) 
        var marker${location.id} = new google.maps.Marker(myMarkerOptions${location.id}); 
      </g:each> 

     } 
    }); 

}

我可以訪問˚F從地圖封閉返回的視圖位置列表中,但我無法訪問搜索實例。 任何想法?

+0

GSP中的'$ {}''內是否已經有'geocoder.geocode({...})'部分? – Pat

+0

不,它在JavaScript腳本中,但不在$ {}中 –

回答

1

如果您將該類的實例作爲模型從控制器傳遞到您的視圖,則可以像往常一樣訪問這些字段。

Controller: searchController { 
    def search = { 
     def searchInstance = Search.get(1) //assuming this gets the search that you want 
     [search:searchInstance] // return searchInstance to the view under the alias search 
    } 
} 

Gsp: search.gsp { 
    geocoder.geocode({ 
     'address': ${search.city} 
    }, 
} 
+0

您的解決方案看起來像我需要的,但它不適合我。也許是因爲我需要城市字段,而不是在search.gsp中,而是在map.gsp中。我在控制器中有一個叫做map的額外的閉包,我用它來調用map.gsp。它給出了例外:無法在空對象上獲取屬性「城市」 –

+0

它畢竟沒有給出任何錯誤。但是這個觀點從未出現。請參閱問題的更新以檢查代碼。 –

+0

我發現了錯誤。我必須在引號內調用搜索實例,如下所示:'address':「$ {search.city}」 –