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

假如想象 提交于 2019-12-10 11:05:50

问题


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

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