Created
August 29, 2018 14:46
-
-
Save m-x-k/baeaeff2df0816c6a6428d362c7fa956 to your computer and use it in GitHub Desktop.
Spring Thymeleaf Extension Dialect Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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