脚本视图
脚本模板
你可以声明一个 ScriptTemplateConfigurer Bean 来指定要使用的脚本引擎、
要加载的脚本文件、用于渲染模板的函数等等。
以下示例使用了 Jython Python 引擎:
-
Java
-
Kotlin
-
Xml
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.scriptTemplate();
}
@Bean
public ScriptTemplateConfigurer configurer() {
ScriptTemplateConfigurer configurer = new ScriptTemplateConfigurer();
configurer.setEngineName("jython");
configurer.setScripts("render.py");
configurer.setRenderFunction("render");
return configurer;
}
}
@Configuration
class WebConfiguration : WebMvcConfigurer {
override fun configureViewResolvers(registry: ViewResolverRegistry) {
registry.scriptTemplate()
}
@Bean
fun configurer() = ScriptTemplateConfigurer().apply {
engineName = "jython"
setScripts("render.py")
renderFunction = "render"
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:view-resolvers>
<mvc:script-template/>
</mvc:view-resolvers>
<mvc:script-template-configurer engine-name="jython" render-function="render">
<mvc:script location="render.py"/>
</mvc:script-template-configurer>
</beans>
render 函数将使用以下参数进行调用:
-
String template:模板内容 -
Map model:视图模型 -
RenderingContext renderingContext:RenderingContext,它提供对应用程序上下文、区域设置、模板加载器和 URL 的访问权限。
控制器用于填充模型属性并指定视图名称,如下例所示:
-
Java
-
Kotlin
@Controller
public class SampleController {
@GetMapping("/sample")
public String test(Model model) {
model.addAttribute("title", "Sample title");
model.addAttribute("body", "Sample body");
return "template";
}
}
@Controller
class SampleController {
@GetMapping("/sample")
fun test(model: Model): String {
model["title"] = "Sample title"
model["body"] = "Sample body"
return "template"
}
}