Search code examples
nunjucks

How to suppress warning when Nunjucks template does not exist?


When calling nunjucksEnvironment.render(“does-not-exist”, context) an error is thrown.

How can I suppress that error? Alternatively, how can I check to see if a template exists before calling .render using whatever template loader is being used to resolve the template?

I am able to wrap the calling of the render method within a try/catch statement but I don’t want to eat all templating errors.


Solution

  • nunjucksEnvironment has getTemplate method, i guess you could wrap it to check that template exist.

    function hasTemplate(templatePath) {
      try {
        nunjucksEnvironment.getTemplate(templatePath);
        return true;
      } catch {
        return false;
      }
    }