Thymeleaf - check if a template exists

Viewed 1803

I am searching a way to check if a template exists before returning it in a view with Thymeleaf and Spring.

In my controller i was trying to do something like this:

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

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

but the exception is not catch...

2 Answers

StringTemplateResource from the comment above seems to return true in every case for thymeleaf 3.0. Here is a method to do this for classpath included templates:

  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();
  }

Testcase:

  @Test
  public void testNonExisting()
  {
    assertFalse(templateExists("foo"));
  }

  @Test
  public void testExisting()
  {
    assertTrue(templateExists("foo.txt"));
  }

Assuming a classpath resource templates/foo.txt exists.

Related