对于最新稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

Groovy 标记

Groovy Markup 模板引擎主要用于生成类 XML 的标记(如 XML、XHTML、HTML5 等),但你也可以用它来生成任何基于文本的内容。Spring Framework 内置了对在 Spring MVC 中使用 Groovy Markup 的集成支持。spring-doc.cadn.net.cn

Groovy 标记模板引擎需要 Groovy 2.3.1 或更高版本。

配置

以下示例展示了如何配置 Groovy 标记模板引擎:spring-doc.cadn.net.cn

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		registry.groovy();
	}

	// Configure the Groovy Markup Template Engine...

	@Bean
	public GroovyMarkupConfigurer groovyMarkupConfigurer() {
		GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer();
		configurer.setResourceLoaderPath("/WEB-INF/");
		return configurer;
	}
}
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {

	override fun configureViewResolvers(registry: ViewResolverRegistry) {
		registry.groovy()
	}

	// Configure the Groovy Markup Template Engine...

	@Bean
	fun groovyMarkupConfigurer() = GroovyMarkupConfigurer().apply {
		resourceLoaderPath = "/WEB-INF/"
	}
}

以下示例展示了如何在 XML 中进行相同的配置:spring-doc.cadn.net.cn

<mvc:annotation-driven/>

<mvc:view-resolvers>
	<mvc:groovy/>
</mvc:view-resolvers>

<!-- Configure the Groovy Markup Template Engine... -->
<mvc:groovy-configurer resource-loader-path="/WEB-INF/"/>

例举

与传统的模板引擎不同,Groovy Markup 依赖于一种使用构建器语法的 DSL。以下示例展示了一个 HTML 页面的模板:spring-doc.cadn.net.cn

yieldUnescaped '<!DOCTYPE html>'
html(lang:'en') {
	head {
		meta('http-equiv':'"Content-Type" content="text/html; charset=utf-8"')
		title('My page')
	}
	body {
		p('This is an example of HTML contents')
	}
}