我们将从Thymeleaf 2.1升级到3.0.5。我们当前的设置(升级前)有许多百里叶模板定义并存储在数据库表中 当我们尝试升级到3.x时,我们的2.1代码不再有效......好了,但我们找不到任何关于如何使用Thymeleaf 3.0.5做同样事情的好例子。有没有人实现过这个?
即使是如何实施org.thymeleaf.templateresolver.StringTemplateResolver的一个体面的例子也可能会让我们朝着正确的方向前进......但我们也找不到任何东西。
这就是我们在2.1中使用的:
public class ThymeleafTemplateResolver extends TemplateResolver {
private final static String PREFIX = "";
public ThymeleafTemplateResolver() {
setResourceResolver(new DbResourceResolver());
setResolvablePatterns(Sets.newHashSet(PREFIX + "*"));
}
@Override
protected String computeResourceName(TemplateProcessingParameters params) {
String templateName = params.getTemplateName();
return templateName.substring(PREFIX.length());
}
private class DbResourceResolver implements IResourceResolver {
@Override
public InputStream getResourceAsStream(TemplateProcessingParameters params, String template) {
ThymeleafTemplateDao thymeleaftemplateDao = ApplicationContextProvider.getApplicationContext().getBean(ThymeleafTemplateDao.class);
ThymeleafTemplate thymeleafTemplate = thymeleaftemplateDao.findByTemplate(template);
if (thymeleafTemplate != null) {
return new ByteArrayInputStream(thymeleafTemplate.getContent().getBytes());
}
return null;
}
@Override
public String getName() {
return "dbResourceResolver";
}
}
}
感谢任何帮助...
答案 0 :(得分:7)
通过大多数的反复试验,我能够把它拼凑起来。将它发布在这里以帮助下一个寻找类似事物的人。
在较新版本的Thymeleaf中,这一过程变得更加容易。现在需要做的就是扩展StringTemplateResolver。
import java.util.Map;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.templateresolver.StringTemplateResolver;
import org.thymeleaf.templateresource.ITemplateResource;
import com.google.common.collect.Sets;
public class ThymeleafDatabaseResourceResolver extends StringTemplateResolver {
private final static String PREFIX = "";
@Autowired ThymeleafTemplateDao thymeleaftemplateDao;
public ThymeleafDatabaseResourceResolver() {
setResolvablePatterns(Sets.newHashSet(PREFIX + "*"));
}
@Override
protected ITemplateResource computeTemplateResource(IEngineConfiguration configuration, String ownerTemplate, String template, Map<String, Object> templateResolutionAttributes) {
// ThymeleafTemplate is our internal object that contains the content.
// You should change this to match you're set up.
ThymeleafTemplateDao thymeleaftemplateDao = ApplicationContextProvider.getApplicationContext().getBean(ThymeleafTemplateDao.class);
ThymeleafTemplate thymeleafTemplate = thymeleaftemplateDao.findByTemplateName(template);
if (thymeleafTemplate != null) {
return super.computeTemplateResource(configuration, ownerTemplate, thymeleafTemplate.getContent(), templateResolutionAttributes);
}
return null;
}
}