我正在寻找一种在Thymeleaf和Spring视图中返回模板之前检查模板是否存在的方法。
在我的控制器中,我正在尝试执行以下操作:
String finalTemplate = template.getPrefix() + "/" + templateName;
try {
return finalTemplate;
} catch(TemplateInputException e) {
logger.debug("Sono qua");
return templateName;
}
但是没有捕获到异常...
答案 0 :(得分:0)
答案 1 :(得分:0)
StringTemplateResource
似乎在每种情况下都返回 true。这是对包含类路径的模板执行此操作的方法:
public static String baseDir = "templates";
/**
* Check if a template exists in subfolder templates.
*
* @param templateName relative name of template below the basedir.
* @return true if exists, otherwise false
*/
public static boolean templateExists(final String templateName)
{
final ClassLoaderTemplateResource iTemplateResource =
new ClassLoaderTemplateResource(baseDir + "/" + templateName, "UTF8");
return iTemplateResource.exists();
}
测试用例:
@Test
public void testNonExisting()
{
assertFalse(templateExists("foo"));
}
@Test
public void testExisting()
{
assertTrue(templateExists("foo.txt"));
}
假设存在类路径资源 templates/foo.txt
。