1. 程式人生 > >Springboot freemark自定義標籤

Springboot freemark自定義標籤

spring-boot開發網站使用freemarker裡的自定義標籤方法

建立類實現 TemplateDirectiveModel 類

@Component
public class UserTopicDirective implements TemplateDirectiveModel {

  @Autowired
  private UserService userService;
  @Autowired
  private TopicService topicService;

  @Override
  public void execute(Environment environment, Map map, TemplateModel[] templateModels,
                      TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
    Page<Topic> page = new PageImpl<>(new ArrayList<>());
    if (map.containsKey("username") && map.get("username") != null) {
      String username = map.get("username").toString();
      if (map.containsKey("p")) {
        int p = map.get("p") == null ? 1 : Integer.parseInt(map.get("p").toString());
        int limit = Integer.parseInt(map.get("limit").toString());
        User currentUser = userService.findByUsername(username);
        if (currentUser != null) {
          page = topicService.findByUser(p, limit, currentUser);
        }
      }
    }
    DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
    environment.setVariable("page", builder.build().wrap(page));
    templateDirectiveBody.render(environment.getOut());
  }
}

建立配置類

@Component
public class FreemarkerConfig {
 
  @Autowired
  private Configuration configuration;
  @Autowired
  private UserTopicDirective userTopicDirective;
 
  @PostConstruct
  public void setSharedVariable() throws TemplateModelException {
    configuration.setSharedVariable("user_topics_tag", userTopicDirective);
  }
 
}

用法

跟自定義macro用法一樣,直接使用 <@xx></@xx> 來使用即可,值就直接在 user_topics_tag 標籤裡傳就可以了

<@user_topics_tag username='tomoya' p=1 limit=10>
  <#list page.getContent() as topic>
    <p>${topic.title!}</p>
  </#list>
</@user_topics_tag>

擴充套件

FreemarkerConfig類不止可以加入自定義的標籤,還可以加入系統自定義的變數等,下面舉例說明

spring-boot裡的配置檔案

# application.yml
site:
  baseUrl: http://localhost:8080/

對應的類是 SiteConfig.java 要取裡面的值,使用方法如下

@Autowired
private SiteConfig siteConfig;

//...
siteConfig.getBaseUrl();

如果把siteConfig加入到freemarker的configuration裡就可以直接在freemarker頁面上使用變量了

@PostConstruct
public void setSharedVariable() throws TemplateModelException {
  configuration.setSharedVariable("site", siteConfig);
  configuration.setSharedVariable("user_topics_tag", userTopicDirective);
}

頁面裡就可以這樣來取值

<a href="${site.bashUrl}">首頁</a>