API / Apache FreeMarker Interview questions
How does FreeMarker resolve template paths when a MultiTemplateLoader chains several loaders together?
MultiTemplateLoader wraps an ordered array of other TemplateLoader instances. When Configuration.getTemplate() asks it for a name, it asks each delegate loader in turn, in the exact order they were supplied, and returns the source from the first one that can find it - later loaders in the list are never even asked once an earlier one succeeds.
TemplateLoader[] loaders = { new FileTemplateLoader(themeOverrideDir), // checked first new ClassTemplateLoader(MyApp.class, "/templates") // fallback }; cfg.setTemplateLoader(new MultiTemplateLoader(loaders));
This ordering is exactly what makes theme overrides possible: put a customer-specific override directory first and the shared default templates second, and any file present in the override directory wins automatically. If none of the delegates find the template, the overall lookup fails and Configuration.getTemplate() raises TemplateNotFoundException, just as it would for a single loader.
Every successful lookup is still cached by the outer Configuration using the resolved name, so the chain of delegate loaders is only actually walked again once the cached entry goes stale, not on every request.
More Related questions...