我能够获得以下 groovy 脚本返回的 xml。但是,如何在页面中获取输出?谁能帮助我如何创建内容模型,使用该模型创建内容项,并让 FreeMarker 模板基于该模型生成 HTML。
提前致谢。
import org.craftercms.core.cache.CacheLoader
import org.craftercms.core.service.CachingOptions
import groovy.json.JsonSlurper
def cacheService = applicationContext["crafter.cacheService"]
def cacheContext = siteContext.getContext()
def myCacheKey = "aServiceCallResponse"
def loader = new ExternalServiceLoader()
def value = ""
def responseItem = cacheService.get(cacheContext, myCacheKey)
if(responseItem == null) {
def myObject = loader.load()
value = myObject
// cache the value with a loader to periodically refresh its value
def cachingOptions = CachingOptions.DEFAULT_CACHING_OPTIONS
try {
cacheService.put(cacheContext, myCacheKey, myObject, [], cachingOptions, loader)
}
catch(err) {
logger.error("error adding ${myCacheKey} to cache: ${err}")
}
}
else {
value = responseItem
}
return value
class ExternalServiceLoader implements CacheLoader {
Object load(Object... parameters) throws Exception {
def externalServiceHost = "http://api.population.io/1.0"
def externalServiceURL = "/population/United%20States/today-and-tomorrow/"
// call the service
def response = (externalServiceHost+externalServiceURL).toURL().getText()
// parse service's the JSON response to an object
def result = new JsonSlurper().parseText( response )
return result
}
}