All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.luues.tool.template.engine.enjoy.EnjoyEngine Maven / Gradle / Ivy

There is a newer version: 2.0.1.RELEASE
Show newest version
package cn.luues.tool.template.engine.enjoy;

import cn.luues.tool.core.io.FileUtil;
import cn.luues.tool.core.util.IdUtil;
import cn.luues.tool.core.util.ObjectUtil;
import cn.luues.tool.template.Template;
import cn.luues.tool.template.TemplateConfig;
import cn.luues.tool.template.TemplateEngine;
import com.jfinal.template.source.FileSourceFactory;

/**
 * Enjoy库的引擎包装
 *
 * @author Mr-Wu
 * @since 4.1.10
 */
public class EnjoyEngine implements TemplateEngine {

	private com.jfinal.template.Engine engine;
	private TemplateConfig.ResourceMode resourceMode;

	// --------------------------------------------------------------------------------- Constructor start

	/**
	 * 默认构造
	 */
	public EnjoyEngine() {}

	/**
	 * 构造
	 *
	 * @param config 模板配置
	 */
	public EnjoyEngine(TemplateConfig config) {
		init(config);
	}

	/**
	 * 构造
	 *
	 * @param engine {@link com.jfinal.template.Engine}
	 */
	public EnjoyEngine(com.jfinal.template.Engine engine) {
		init(engine);
	}
	// --------------------------------------------------------------------------------- Constructor end

	@Override
	public TemplateEngine init(TemplateConfig config) {
		if(null == config){
			config = TemplateConfig.DEFAULT;
		}
		this.resourceMode = config.getResourceMode();
		init(createEngine(config));
		return this;
	}

	/**
	 * 初始化引擎
	 * @param engine 引擎
	 */
	private void init(com.jfinal.template.Engine engine){
		this.engine = engine;
	}

	@Override
	public Template getTemplate(String resource) {
		if(null == this.engine){
			init(TemplateConfig.DEFAULT);
		}
		if (ObjectUtil.equal(TemplateConfig.ResourceMode.STRING, this.resourceMode)) {
			return EnjoyTemplate.wrap(this.engine.getTemplateByString(resource));
		}
		return EnjoyTemplate.wrap(this.engine.getTemplate(resource));
	}

	/**
	 * 创建引擎
	 *
	 * @param config 模板配置
	 * @return {@link com.jfinal.template.Engine}
	 */
	private static com.jfinal.template.Engine createEngine(TemplateConfig config) {
		final com.jfinal.template.Engine engine = com.jfinal.template.Engine.create("Hutool-Enjoy-Engine-" + IdUtil.fastSimpleUUID());
		engine.setEncoding(config.getCharsetStr());

		switch (config.getResourceMode()) {
			case STRING:
				// 默认字符串类型资源:
				break;
			case CLASSPATH:
				engine.setToClassPathSourceFactory();
				engine.setBaseTemplatePath(config.getPath());
				break;
			case FILE:
				engine.setSourceFactory(new FileSourceFactory());
				engine.setBaseTemplatePath(config.getPath());
				break;
			case WEB_ROOT:
				engine.setSourceFactory(new FileSourceFactory());
				engine.setBaseTemplatePath(FileUtil.getAbsolutePath(FileUtil.getWebRoot()));
				break;
			default:
				break;
		}

		return engine;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy