【问题标题】:Programmatically consume html template with Groovy/Grails使用 Groovy/Grails 以编程方式使用 html 模板
【发布时间】:2012-11-13 23:54:22
【问题描述】:

我正在尝试使用带有 Grails 应用程序的 html 模板。我得到了一个 URL,需要在运行时将 html 动态加载到我的 Grails 视图中。在 HTML 代码中有一个 {title} 和一个 {content} 标记,我的 Grails 代码将被注入其中。

在 PHP 中,它类似于 include("url");现在我们如何在 Grails 中做到这一点,或者有可能吗?

【问题讨论】:

标签: html grails groovy


【解决方案1】:

如果没有缓存,也没有真正诱人的 solition,您的代码可能如下所示:

def template = new Url('http://example.com').getText()
def html
html = html.replaceAll('{title}','my Title')
html = html.replaceAll('{content}','my Content')

但 Raphael 绝对正确:如果您需要更复杂的解决方案 (http://groovy.codehaus.org/Groovy+Templates),则应该查看 groovy 模板框架。

使用模板框架,您首先要准备模板

import groovy.text.SimpleTemplateEngine
def template = new Url('http://example.com').getText()
template = template.replaceAll('{title}','${title}')
template = tamplate.replaceAll('{content}','${content}')

并将其作为缓存保存到数据库中。当您必须扩大您的 HTML 页面时,您可以获取模板并让 groovy 替换占位符:

def binding = [title:"my Title", content:"my Content"]
def engine = new SimpleTemplateEngine()
html = engine.createTemplate(template).make(binding)

就是这样。

【讨论】:

    猜你喜欢
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 2013-07-07
    • 2015-12-09
    • 1970-01-01
    • 2022-06-13
    相关资源
    最近更新 更多