使用thymeleaf 3处理字符串模板

时间:2016-08-21 09:29:37

标签: spring thymeleaf

我们可以使用StringTemplateResolver使用Icontext填充字符串模板。如果是这样我们怎么办? 从Thymeleaf 3中删除了TemplateProcessingParameters和IResourceResolver。任何工作示例都会有很大帮助吗?

我遵循了这个例子,它在Thymeleaf 2中很有效 Is there a way to make Spring Thymeleaf process a string template?

我也没有看到任何参考迁移指南。

3 个答案:

答案 0 :(得分:4)

我想我找到了解决方案。如果有人有更好的答案,请告诉我。 我之前犯了一个小错误。希望这会有所帮助。

private TemplateEngine templateEngine;

private TemplateEngine getTemplateEngine() {
        if(null == templateEngine){
            templateEngine = new TemplateEngine();
            StringTemplateResolver templateResolver =new   StringTemplateResolver();
            templateResolver.setTemplateMode(TemplateMode.HTML);
            templateEngine.setTemplateResolver(templateResolver);
        }
        return templateEngine;
    }




public String getTemplateFromMap(String htmlContent, Map<String, String> dynamicAttibutesMap) {
    templateEngine = getTemplateEngine();
    String template = null;
    final Context ctx = new Context(new Locale(TEMPLATE_LOCAL));
    if (!CollectionUtils.isEmpty(emailAttibutesMap)) {
        dynamicAttibutesMap.forEach((k,v)->ctx.setVariable(k, v));
    }
    if (null != templateEngine) {
        template = templateEngine.process(htmlContent, ctx);
    } 
    return template;
}

答案 1 :(得分:3)

这就是我们这样做的方式,作为 Spring @Service Bean

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateProcessingParameters;
import org.thymeleaf.context.IContext;
import org.thymeleaf.messageresolver.IMessageResolver;
import org.thymeleaf.messageresolver.StandardMessageResolver;
import org.thymeleaf.resourceresolver.IResourceResolver;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.templatemode.StandardTemplateModeHandlers;
import org.thymeleaf.templateresolver.ITemplateResolutionValidity;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresolver.NonCacheableTemplateResolutionValidity;
import org.thymeleaf.templateresolver.TemplateResolution;
import org.thymeleaf.util.Validate;
import com.rathna.app.model.constants.common.BeanConstants;

/**
 * Ref: https://github.com/thymeleaf/thymeleaf-itutorial/blob/2.1-master/src/test/java/org/thymeleaf/tools/memoryexecutor/StaticTemplateExecutorTest.java
 * @author anandchakru
 *
 */
@Service
public class StaticTemplateService {
    public String processTemplateCode(final String code, final IContext context) {
        Validate.notNull(code, "Code must be non-null");
        Validate.notNull(context, "Context must be non-null");
        String templateMode = StandardTemplateModeHandlers.HTML5.getTemplateModeName();
        IMessageResolver messageResolver = new StandardMessageResolver();
        ITemplateResolver templateResolver = new MemoryTemplateResolver(code, templateMode);
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setMessageResolver(messageResolver);
        templateEngine.setTemplateResolver(templateResolver);
        templateEngine.initialize();
        return templateEngine.process("dummy", context);
    }
}

class FixedMemoryResourceResolver implements IResourceResolver {
    private static final String NAME = "FixedMemoryResourceResolver";
    private final String templateContent;

    public FixedMemoryResourceResolver(final String templateContent) {
        Validate.notNull(templateContent, "Template content must be non-null");
        this.templateContent = templateContent;
    }
    @Override
    public String getName() {
        return NAME;
    }
    @Override
    public InputStream getResourceAsStream(final TemplateProcessingParameters tpp, final String templateName) {
        return new ByteArrayInputStream(templateContent.getBytes());
    }
}

class MemoryTemplateResolver implements ITemplateResolver {
    private static final String NAME = "MemoryTemplateResolver";
    private static final Integer ORDER = 1;
    private final String templateContent;
    private final String templateMode;

    public MemoryTemplateResolver(final String templateContent, final String templateMode) {
        Validate.notNull(templateContent, "Template content must be non-null");
        Validate.notNull(templateMode, "Template mode must be non-null");
        this.templateContent = templateContent;
        this.templateMode = templateMode;
    }
    @Override
    public void initialize() {
    }
    @Override
    public String getName() {
        return NAME;
    }
    @Override
    public Integer getOrder() {
        return ORDER;
    }
    @Override
    public TemplateResolution resolveTemplate(final TemplateProcessingParameters tpp) {
        String templateName = "CustomTemplate";
        String resourceName = "CustomResource";
        IResourceResolver resourceResolver = new FixedMemoryResourceResolver(templateContent);
        ITemplateResolutionValidity validity = new NonCacheableTemplateResolutionValidity();
        return new TemplateResolution(templateName, resourceName, resourceResolver, StandardCharsets.UTF_8.toString(),
                templateMode, validity);
    }
}

并将其称为:

@Autowired
protected StaticTemplateService staticTemplateService;
...
private String getProcessedHtml(){
    Context context2 = new Context();
    context2.setVariable("greet", "Hello");
    return staticTemplateService.processTemplateCode("<div th:text="${greet}">Hi</div> World", context2);
}

答案 2 :(得分:1)

使用Spring 5和百里香叶的最新版本,它易于从百里香叶中读取字符串。

如果您使用gradle,请使用以下导入

compile "org.thymeleaf:thymeleaf:3.0.11.RELEASE"
compile "org.thymeleaf:thymeleaf-spring5:3.0.11.RELEASE"

//Code sample starts here
private TemplateEngine templateEngine;

private final static String TEMPLATE_LOCAL = "US";


public TemplateEngine getTemplateEngine() {
    templateEngine = new TemplateEngine();
    StringTemplateResolver stringTemplateResolver = new StringTemplateResolver();
    templateEngine.setTemplateResolver(stringTemplateResolver);
    return templateEngine;
}   



public String getTemplateFromAttributes(String htmlContent, Map<String, Object> attr) 
 {
        templateEngine = getTemplateEngine();
        Context context = new Context(new Locale(TEMPLATE_LOCAL));
        if (!CollectionUtils.isEmpty(attr)) {
            attr.forEach((k,v)->context.setVariable(k, v));
        }
        return templateEngine.process(htmlContent, context);        
}

希望这是一个有用的代码段