1

我能够获得以下 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
    }
 }
4

1 回答 1

2

你目前有什么样的 groovy 脚本?另外,您使用的是 CrafterCMS 3.x 吗?

如果您已经将其作为 REST 脚本,那么最简单的方法可能是通过 JavaScript(即 AJAX)调用您的服务来在客户端呈现它。然后,您可以使用调用中的数据以您喜欢的任何方式呈现页面 - 例如 React、Vue、jQuery。如果这样做,最好返回 JSON 而不是 XML。

如果您想走 FTL 路径,据我从您的问题中了解到,听起来您需要将您的 groovy 脚本设置为控制器脚本。那些需要返回到您要渲染的 FTL 的路径,并且它们需要在{site}/scripts/controllers/*. 从模板中,您可以访问templateModel您放入其中的任何道具。

查看文档:https ://docs.craftercms.org/en/3.0/developers/projects/engine/api/groovy-api.html

你问题的第二部分......

谁能帮助我如何创建内容模型,使用该模型创建内容项,并让 FreeMarker 模板基于该模型生成 HTML。

通常,要创建内容模型,您需要转到site config > content types > "Create new type". 创建新类型时,您必须将模型(内容类型)与模板相关联。然后要创建内容项,请转到您的站点仪表板,然后从Pages树中右键单击以创建New Content并选择您最近创建的内容类型。从那里开始,一切都会自动运行(FTL、渲染、FTL 中可用的模型变量等)

如果这些更适合您正在做的事情,您还可以创建组件而不是页面。

于 2019-02-24T06:00:04.970 回答