How to check the existense of a freemarker template before include it

可紊 提交于 2019-12-06 08:48:36

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!");
      }
    }
  }

}

The

<#attempt>
<#recover>
</#attempt>

statement should do the trick.

Look here http://freemarker.sourceforge.net/docs/ref_directive_attempt.html for further information.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!