Skip to content

Instantly share code, notes, and snippets.

@m-x-k
Created August 29, 2018 14:46
Show Gist options
  • Save m-x-k/baeaeff2df0816c6a6428d362c7fa956 to your computer and use it in GitHub Desktop.
Save m-x-k/baeaeff2df0816c6a6428d362c7fa956 to your computer and use it in GitHub Desktop.
Spring Thymeleaf Extension Dialect Example
@Configuration
public class ThymeLeafConfig {
@Autowired
private SpringResourceTemplateResolver templateResolver;
@Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setEnableSpringELCompiler(true);
templateEngine.setTemplateResolver(templateResolver);
templateEngine.addDialect(new MyDialect());
return templateEngine;
}
}
class MyDialect extends AbstractProcessorDialect {
public MyDialect() {
super("My Dialect", "example", StandardDialect.PROCESSOR_PRECEDENCE);
}
@Override
public Set<IProcessor> getProcessors(String dialectPrefix) {
Set<IProcessor> processors = new HashSet<>();
processors.add(new MyCSSTagProcessor(dialectPrefix));
return processors;
}
}
class MyCSSTagProcessor extends AbstractAttributeTagProcessor {
/*
* Example usage: <i example:updateCSS="${value}"></i>
*/
private static final String ATTR_NAME = "updateCSS";
private static final int PRECEDENCE = 10000;
public MyCSSTagProcessor(String dialectPrefix) {
super(TemplateMode.HTML, dialectPrefix, null, false, ATTR_NAME, true, PRECEDENCE, true);
}
@Override
protected void doProcess(ITemplateContext context,
IProcessableElementTag tag,
AttributeName attributeName,
String attributeValue,
IElementTagStructureHandler structureHandler) {
IEngineConfiguration configuration = context.getConfiguration();
IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration);
IStandardExpression expression = parser.parseExpression(context, attributeValue);
String value = (String) expression.execute(context);
structureHandler.setAttribute("class", value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment