首页 > 解决方案 > Apache Velocity GenericTools ToolsManager 不工作

问题描述

我正在使用 Apache Velocity 模板引擎仅从字符串呈现。我已经使它与下面的代码一起工作,但 ToolManager 似乎没有工作。通过以下设置,我无法使用此处定义的任何默认工具https://github.com/apache/velocity-tools/blob/8e7f20a4/velocity-tools-generic/src/main/resources/org/apache/velocity/ tools/generic/tools.xml
例如,来自 DateTool 的 $date 不起作用。

@Service
public class VelocityServiceImpl implements VelocityService {

    private final VelocityEngine velocityEngine;
    private final ToolContext toolContext;

    public VelocityServiceImpl() {
        Properties properties = new Properties();
        properties.setProperty("resource.loader", "class");
        properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

        properties.setProperty(RuntimeConstants.EVENTHANDLER_INCLUDE, IncludeRelativePath.class.getName());

        this.velocityEngine = new VelocityEngine();
        this.velocityEngine.init(properties);

        ToolManager manager = new ToolManager();
        manager.setVelocityEngine(this.velocityEngine);
        this.toolContext = manager.createContext();
    }

    @Override
    public String getTemplateFromString(String template, Map<String, Object> context) throws IOException {
        if (template == null) {
            template = "";
        }

        Writer writer = new StringWriter();

        VelocityContext velocityContext = new VelocityContext(context, this.toolContext);

        this.velocityEngine.evaluate(velocityContext, writer, "getTemplateFromString: ", template);
        writer.flush();
        return writer.toString();
    }
}

我的依赖:

    implementation group: 'org.apache.velocity', name: 'velocity', version: '1.7'
    implementation group: 'org.apache.velocity', name: 'velocity-engine-core', version: '2.3'
    implementation group: 'org.apache.velocity.tools', name: 'velocity-tools-generic', version: '3.1'
    implementation group: 'commons-beanutils', name: 'commons-beanutils', version: '1.9.4'

有什么我想念的想法吗?

标签: velocity

解决方案


推荐阅读