跳到主要内容
版本:7.0.3

脚本视图

Hunyuan 7b 中英对照 Script Views

Spring框架内置了集成机制,可以将Spring MVC与任何能够在JSR-223 Java脚本引擎上运行的模板库结合使用。我们已经在不同的脚本引擎上测试了以下模板库:

脚本库脚本引擎
ERBJRuby
字符串模板Jython
提示

整合任何其他脚本引擎的基本规则是,该引擎必须实现ScriptEngineInvocable接口。

要求

你需要在类路径(classpath)中包含脚本引擎,不同脚本引擎的详细要求有所不同:

  • 应将 JRuby 添加为依赖项,以支持 Ruby。
  • 应将 Jython 添加为依赖项,以支持 Python。

脚本模板

你可以声明一个ScriptTemplateConfigurerbean来指定要使用的脚本引擎、要加载的脚本文件、调用哪个函数来渲染模板等等。以下示例使用了Jython Python引擎:

@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;
}
}

渲染函数使用以下参数被调用:

  • String template:模板内容
  • Map model:视图模型
  • RenderingContext renderingContextRenderingContext,它提供了对应用程序上下文、区域设置(locale)、模板加载器以及URL的访问权限

控制器用于填充模型属性并指定视图名称,如下例所示:

@Controller
public class SampleController {

@GetMapping("/sample")
public String test(Model model) {
model.addAttribute("title", "Sample title");
model.addAttribute("body", "Sample body");
return "template";
}
}

可以查看Spring Framework的单元测试,Java版本,以及资源文件,以获取更多配置示例。