私は、アプリケーションページのテンプレートエンジンとしてThymeleaf 3を使用するSpring Bootアプリケーションを持っています。 spring-boot-starter-thymeleafで提供されるデフォルト設定を使用し、HTML Thymeleafテンプレートはsrc/main/resources/templatesフォルダにあります。複数のThymeleafテンプレートモードのサポートを追加する方法
ここで、新しいJavaScriptテンプレートモードを使用して、いくつかのjavascriptファイルを生成するためにThymeleafを使用したいと思います。それらのjavascriptテンプレートは、同じHTMLテンプレートフォルダまたは別のテンプレートフォルダ(例:src/main/resources/jstemplates)に配置できます。
spring-boot-starter-thymeleafで提供されているデフォルト設定で何も変更せずにこの設定を追加する方法があるかどうかわからない、またはすべての設定を完全に作成する必要があります。
私はjavascriptテンプレートで動作する次の設定で最初のオプションを試しましたが、htmlテンプレートはもう動作しません。
設定:
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter
implements ApplicationContextAware {
private static final String UTF8 = "UTF-8";
@Autowired
private SpringTemplateEngine templateEngine;
@Autowired
private ThymeleafProperties properties;
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
public ThymeleafViewResolver javascriptThymeleafViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(this.templateEngine);
resolver.setCharacterEncoding(UTF8);
resolver.setContentType("application/javascript");
resolver.setViewNames(new String[] {".js"});
resolver.setCache(this.properties.isCache());
return resolver;
}
@Bean
public SpringResourceTemplateResolver javascriptTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("classpath:/jstemplates/");
resolver.setSuffix(".js");
resolver.setTemplateMode(TemplateMode.JAVASCRIPT);
resolver.setCharacterEncoding(UTF8);
return resolver;
}
}
テストジャバスクリプトコントローラ:
@Controller
public class JavascriptController {
@RequestMapping(method = RequestMethod.GET, value = "/test.js")
public String testjs() {
return "test";
}
}
ルートページ用コントローラ:
@Controller
public class MainController {
@RequestMapping(method = RequestMethod.GET, value = "/")
public String index(Model model) {
return "index";
}
}
でtest.jsファイルがありますsrc/main/resources/jstemplat esフォルダー。私がURL http://localhost:8080/test.jsを試しても、期待どおりに動作します。私がしようとした場合でも、例えば、メインのURL(http://localhost:8080/)それは次のエラーで失敗します。それはjavascriptTemplateResolver思えるよう
がCaused by: java.io.FileNotFoundException: class path resource [jstemplates/index.js] cannot be opened because it does not exist
それは、代わりにテンプレート/ index.htmlをを探しているべきですそれを元に戻すことなく、デフォルトのものよりも優先されます。
デフォルトのThymeleaf設定と統合された別のテンプレートモードサポートを追加する方法はありますか、またはすべてをゼロから設定する必要がありますか?