我尝试在我的 Java Spring 应用程序中实现 Jade4J。不幸的是,它找不到模板文件。
JadeConfig.java
@Configuration
@EnableWebMvc
public class JadeConfig {
@Bean
public SpringTemplateLoader templateLoader() {
SpringTemplateLoader templateLoader = new SpringTemplateLoader();
templateLoader.setBasePath("classpath:/templates/");
templateLoader.setEncoding("UTF-8");
templateLoader.setSuffix(".jade");
return templateLoader;
}
@Bean
public JadeConfiguration jadeConfiguration() {
JadeConfiguration configuration = new JadeConfiguration();
configuration.setCaching(false);
configuration.setTemplateLoader(templateLoader());
return configuration;
}
@Bean
public ViewResolver viewResolver() {
JadeViewResolver viewResolver = new JadeViewResolver();
viewResolver.setConfiguration(jadeConfiguration());
return viewResolver;
}
}
Controller .java
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/test")
public static String render() throws JadeCompilerException, IOException {
List<Book> books = new ArrayList<Book>();
books.add(new Book("The Hitchhiker's Guide to the Galaxy", 5.70, true));
Map<String, Object> model = new HashMap<String, Object>();
model.put("books", books);
model.put("pageName", "My Bookshelf");
return Jade4J.render("index", model);
}
}
它始终显示错误“(没有这样的文件或目录)”。知道这里有什么问题吗?
最佳答案
- 您应该有一个
@Controller
,而不是 @RestController(对于 Json、XML),因为您尝试使用 Jade 渲染 HTML。 - 不要自己调用 Jade4Render,而是返回
对模板的引用
。然后 Spring 将为您完成渲染。 - 不要将该方法设为静态。
所以你的代码应该看起来像这样(假设在 classpath:/templates/
中存在一个名为 index.jade
的文件)
@Controller
@RequestMapping("/users")
public class UserController {
@GetMapping("/test")
public String render(Model model) {
// add something to the model here, e.g. model.put("books", books);
return index;
}
}
关于java - Jade4J:没有这样的文件或目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61076369/