第一次写,所以直接撸代码
要想自定义标签,一共有3步
1、确定自定义标签,如<myTag myTag=1 class="
customer"></myTag></myTag:myTag>
2、创建自定义标签解析器DictMyTagProcessor,继承 AbstractElementTagProcessor抽象类
代码如下:
public class DictMyTagProcessor extends AbstractElementTagProcessor {
private static final String TAG_NAME = "myTag";
private static final String CLASS = "class";
private static final int PRECEDENCE = 300;
@Override
protected void doProcess(ITemplateContext context, IProcessableElementTag tag,
IElementTagStructureHandler handler) {
IAttribute tagName = tag.getAttribute(TAG_NAME);
IAttribute clas = tag.getAttribute(CLASS);
String tagValue = "<myTag class=" + clas.getValue() + ">自定义标签</myTag>";
handler.replaceWith(tagValue, false);
}
public DialectShowProcess(String dialectPrefix) {
super(TemplateMode.HTML, dialectPrefix, TAG_NAME, true, null, false, PRECEDENCE);
}
}
3、创建Dialect,继承AbstractProcessorDialect抽闲类,将DictMyTagProcessor 处理器加入到处理器集中
代码如下:
public class Dialect extends AbstractProcessorDialect {
private final static String NAME = "myTag";
public Dialect() {
super(NAME, null, StandardDialect.PROCESSOR_PRECEDENCE);
}
@Override
public Set<IProcessor> getProcessors(String dialectPrefix) {
return createStandardProcessorsSet(dialectPrefix);
}
private Set<IProcessor> createStandardProcessorsSet(String dialectPrefix) {
LinkedHashSet<IProcessor> processors = new LinkedHashSet<IProcessor>();
// 添加自定义标签处理器,可添加多个
processors.add(new DictMyTagProcessor (dialectPrefix));
return processors;
}
}
4、配置Dialect
代码如下:
@Configuration
public class DialectConfig {
@Bean
public Dialect getDialect() {
return new Dialect();
}
}
以上即可实现基本的自定义标签功能
结果如下: