/** * 模板引擎 —— 处理模板并渲染结果 * * @param templateResolver 模板解析器 * @return */ @Bean public SpringTemplateEngine springTemplateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine(); springTemplateEngine.setTemplateResolver(templateResolver); //自定义方言 ReqNameDialect reqNameDialect=new ReqNameDialect(); SpringSecurityDialect springSecurityDialect=new SpringSecurityDialect(); springTemplateEngine.addDialect(reqNameDialect); springTemplateEngine.addDialect(springSecurityDialect); return springTemplateEngine; }
自定义标签处理类
这个主要是处理内容显示和隐藏
public class ProcessorNew extends AbstractStandardConditionalVisibilityTagProcessor { public ProcessorNew(String dialectPrefix) { super(TemplateMode.HTML, dialectPrefix, "reqNameNew", 100); } @Override protected boolean isVisible(ITemplateContext context, IProcessableElementTag tag, AttributeName attributeName, String attributeValue) { return false; } }
这个主要是对标签参数的处理
public class ReqProcessor extends AbstractAttributeTagProcessor { private static final String TEXT_ATTRIBUTE = "reqName"; private static final int PRECEDENCE = 10000; /*templateMode: 模板模式,这里使用HTML模板。 dialectPrefix: 标签前缀。即xxx:text中的xxx。在此例子中prefix为thSys。 elementName:匹配标签元素名。举例来说如果是div,则我们的自定义标签只能用在div标签中。为null能够匹配所有的标签。 prefixElementName: 标签名是否要求前缀。 attributeName: 自定义标签属性名。这里为text。 prefixAttributeName:属性名是否要求前缀,如果为true,Thymeeleaf会要求使用text属性时必须加上前缀,即thSys:text。 precedence:标签处理的优先级,此处使用和Thymeleaf标准方言相同的优先级。 removeAttribute:标签处理后是否移除自定义属性。*/ public ReqProcessor(String dialectPrefix) { super( TemplateMode.HTML, dialectPrefix, null, false, TEXT_ATTRIBUTE, true, PRECEDENCE, true); } @Override protected void doProcess(ITemplateContext context, IProcessableElementTag tag, AttributeName attributeName, String attributeValue, IElementTagStructureHandler structureHandler) { final IEngineConfiguration configuration = context.getConfiguration(); final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration); final IStandardExpression expression = parser.parseExpression(context, attributeValue); final String title = (String) expression.execute(context); //structureHandler.setBody(title+"blog_name",false); structureHandler.setAttribute("abn","abv"); structureHandler.setAttribute("style","background-color:pink"); } }
html页
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Hello World!</title> </head> <body> <span sec:reqName="abc">123456</span> <span sec:reqNameNew="abc">不可见的标签</span> </body> </html>