thymeleaf教程-springboot项目中实现thymeleaf自定义标签

转载: http://www.9191boke.com/466119140.html    91博客网

开始:

在使用thymeleaf的过程中有时候需要公共部分渲染页面,这个时候使用自定义标签实现自动查询数据进行渲染比较方便,不用额外在每个页面渲染中去分别查询。已网站底部的友情链接设置为例子,下面开始教程。

1.html

html如下:

<div id="friend_link">
            友情链接:
            <div amlink:text="''" style="display: inline">
            </div>
        </div>

可以看出我们需要定义的自定义标签为amlink。

2.实现自定义标签处理器

ThSysTagProcessor

package webapp.customlabel;

import com.baomidou.mybatisplus.mapper.SqlRunner;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.thymeleaf.templatemode.TemplateMode;

import java.util.List;
import java.util.Map;

/**
 * 自定义标签
 */
public class ThSysTagProcessor extends AbstractAttributeTagProcessor {
    private static final String TEXT_ATTRIBUTE  = "text";
    private static final int PRECEDENCE = 10000;

    /*
     templateMode: 模板模式,这里使用HTML模板。
     dialectPrefix: 标签前缀。即xxx:text中的xxx。
     elementName:匹配标签元素名。举例来说如果是div,则我们的自定义标签只能用在div标签中。为null能够匹配所有的标签。
     prefixElementName: 标签名是否要求前缀。
     attributeName: 自定义标签属性名。这里为text。
     prefixAttributeName:属性名是否要求前缀,如果为true,Thymeeleaf会要求使用text属性时必须加上前缀,即xxx:text。
     precedence:标签处理的优先级,此处使用和Thymeleaf标准方言相同的优先级。
     removeAttribute:标签处理后是否移除自定义属性。
     */
    public ThSysTagProcessor(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);

        SqlRunner sqlRunner = new SqlRunner();
        List<Map<String, Object>> mapList = sqlRunner.selectList("select * from amlink order by sort");
        StringBuilder links = new StringBuilder();
        String alink = "<a href=\"#link#\" target=\"_blank\" title=\"#a_title#\">#title#</a>";
        for (Map<String, Object> map : mapList) {
            String alinkStr = alink
                    .replaceAll("#link#", map.get("link").toString())
                    .replaceAll("#a_title#", map.get("a_title").toString())
                    .replaceAll("#title#", map.get("title").toString())
            ;
            links.append(alinkStr);
        }

        structureHandler.setBody(title + links.toString(), false);
    }
}

注:以下为从数据库中查询出友情链接并拼接成一个字符串

springboot项目中实现thymeleaf自定义标签 | 91博客

3.定义方言类ThSysDialect

package webapp.customlabel;

import org.thymeleaf.dialect.AbstractProcessorDialect;
import org.thymeleaf.processor.IProcessor;
import org.thymeleaf.standard.StandardDialect;
import org.thymeleaf.standard.processor.StandardXmlNsTagProcessor;
import org.thymeleaf.templatemode.TemplateMode;

import java.util.HashSet;
import java.util.Set;

public class ThSysDialect extends AbstractProcessorDialect {
    //定义方言名称
    private static final String DIALECT_NAME = "Sys Dialect";

    public ThSysDialect() {
        //设置自定义方言与"方言处理器"优先级相同
        super(DIALECT_NAME, "amlink", StandardDialect.PROCESSOR_PRECEDENCE);
    }

    @Override
    public Set<IProcessor> getProcessors(String dialectPrefix) {
        Set<IProcessor> processors = new HashSet<>();
        processors.add(new ThSysTagProcessor(dialectPrefix));
        processors.add(new StandardXmlNsTagProcessor(TemplateMode.HTML, dialectPrefix));
        return processors;
    }
}

4.在SpringBoot中加载自定义方言

package webapp.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import webapp.customlabel.ThSysDialect;

/**
 * Thymeleaf配置
 */
@Configuration
public class ThymeleafDialectConfig {
    @Bean
    public ThSysDialect thSysDialect() {
        return new ThSysDialect();
    }

}

猜你喜欢

转载自www.cnblogs.com/007sx/p/10963031.html