thymeleaf(3)自定义标签

1、申明自定义标签

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package wxtx.com.thymeleaf;
import java.util.HashSet;
import java.util.Set;
import org.springframework.stereotype.Component;
import org.thymeleaf.processor.IProcessor;
import org.thymeleaf.spring4.dialect.SpringStandardDialect;

@Component
public class TXDialect extends SpringStandardDialect {
public String getPrefix() {
return "wxtx";
}

@Override
public Set<IProcessor> getProcessors() {
final Set<IProcessor> processors = new HashSet<IProcessor>();
processors.add(new TXElementProcessor());
return processors;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import org.thymeleaf.Arguments;
import org.thymeleaf.dom.Element;
import org.thymeleaf.dom.Node;
import org.thymeleaf.dom.Text;
import org.thymeleaf.processor.element.AbstractMarkupSubstitutionElementProcessor;

@Component
public class TXElementProcessor extends AbstractMarkupSubstitutionElementProcessor {
public TXElementProcessor() {
super("hello");
}

@Override
protected List<Node> getMarkupSubstitutes(Arguments arguments, Element element) {
//获取标签name属性的值
String name = element.getAttributeValue("name");
List<Node> nodes = null;

if("none".equals(name)){
//如果name属性的值为none,则在自定义标签下的内容前插入标签:<strong style="color:red">无信息</strong>
Element h2 = new Element("strong");
h2.setAttribute("style", "color:red");
h2.addChild(new Text("无信息"));
element.insertChild(0, h2);
nodes = element.getChildren();
} else {
//如果name属性不为none,则移除自定义标签下的内容,插入<div>hello name</div>
Element container = new Element("div");
String content = "hello "+name;
Text text = new Text(content);
container.addChild(text);
nodes = new ArrayList<>();
nodes.add(container);
}

return nodes;
}

@Override
public int getPrecedence() {
return 1000;
}
}

2、注册自定义标签

2.1、spring4

修改spring配置文件

1
2
3
4
5
6
7
8
9
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver"/>
<property name="dialects">
<set>
<!-- 添加自定义标签 -->
<bean class="wxtx.com.thymeleaf.TXDialect" />
</set>
</property>
</bean>

2.2、springboot

springboot默认使用thymeleaf引擎,所以不需要在配置文件中注册自定义标签,仅需要将自定义标签类添加入spring容器即可。例如添加@Component注解。

3、使用方法

1
2
<wxtx:hello name="小吴">123<strong>456</strong></wxtx:hello>
<wxtx:hello name="none">123<strong>456</strong></wxtx:hello>

4、效果

thymeleaf渲染后的html源码

1
2
<div>hello 小吴</div>
<strong style="color:red">无信息</strong>123<strong>456</strong>

5、获取表达式变量

https://www.thymeleaf.org/doc/articles/sayhelloagainextendingthymeleafevenmore5minutes.html

>