问题
Sometimes I have to use the following snippet :
<#include 'some.ftl' />
Does freemarker have a directive that return the existense of some.ftl ?
Like
<#include_if_exists 'some.ftl' >
Or can I implement such a directive by myself?
回答1:
OK. Resolved by user-directive
[@include template='some.ftl' /]
WARN if template not found...
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import freemarker.core.Environment;
import freemarker.template.Template;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
public class FreemarkerIncludeDirective implements TemplateDirectiveModel {
private static final Logger logger = LoggerFactory.getLogger(FreemarkerIncludeDirective.class);
@Override
public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body) throws TemplateException, IOException {
if (params.containsKey("template")) {
String t = params.get("template").toString();
try {
Template template = env.getTemplateForImporting(t);
env.include(template);
} catch (FileNotFoundException e) {
logger.warn(t + "not found!");
}
}
}
}
回答2:
The
<#attempt>
<#recover>
</#attempt>
statement should do the trick.
Look here http://freemarker.sourceforge.net/docs/ref_directive_attempt.html for further information.
来源:https://stackoverflow.com/questions/13908848/how-to-check-the-existense-of-a-freemarker-template-before-include-it