Thymeleaf-检查模板是否存在

时间:2018-09-02 17:20:15

标签: spring-boot thymeleaf

我正在寻找一种在Thymeleaf和Spring视图中返回模板之前检查模板是否存在的方法。

在我的控制器中,我正在尝试执行以下操作:

String finalTemplate = template.getPrefix() + "/" + templateName;

        try {
            return finalTemplate;
        } catch(TemplateInputException e) {
            logger.debug("Sono qua");
            return templateName;
        }

但是没有捕获到异常...

2 个答案:

答案 0 :(得分:0)

此处处理异常的方式不适用于模板异常。

在问题部分github上检查以下与此相关的线程。

https://github.com/thymeleaf/thymeleaf-spring/issues/94

https://github.com/thymeleaf/thymeleaf-spring/issues/81

答案 1 :(得分:0)

对于 thymeleaf 3.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