欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在Java中FreeMarker?模板來定義字符串模板

 更新時間:2022年04月22日 10:05:43   作者:心城以北?  
這篇文章主要介紹了在Java中FreeMarker?模板來定義字符串模板,文章基于Java的相關(guān)資料展開詳細內(nèi)容,需要的小伙伴可以參考一下

問題描述

  • 一個業(yè)務(wù)需求,需要在后端通過代碼渲染一個,列表如下圖所示(下圖只是一個示意):

image.png

這個表格的特點就是數(shù)據(jù)重復(fù)比較多,結(jié)構(gòu)簡單,我們可以通過 Java 代碼直接拼字符串。但是這樣的問題就會導(dǎo)致,代碼非常的難看。在 Java 代碼中混雜著很多樣式代碼,可讀性和可維護性比較差。所以我就 pass 著這個方案。

于是我就想到,通過模板 + 參數(shù)的方式來實現(xiàn),這樣可以做到結(jié)構(gòu)和參數(shù)的分離,經(jīng)過比較我選擇了通過 FreeMarker 模板來定義結(jié)構(gòu),最終完成字符串模板的定義。

代碼實現(xiàn)

  • 導(dǎo)入依賴,這里我是基于 spring-boot 為基礎(chǔ)的。
implementation 'org.springframework.boot:spring-boot-starter-freemarker'
  • FreeMarker 工具方法,主要是實現(xiàn)模板文件的讀取和渲染。
@Slf4j
public class FreeMarkerUtils {

    static Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);

    static {
        cfg.setEncoding(Locale.ENGLISH, "utf-8");
        cfg.setTemplateLoader(new SpringTemplateLoader(new DefaultResourceLoader(),"templates/"));
    }

    /**
     * 獲取模板
     *
     * @param templateName
     * @return
     */
    public static Template getTpl(String templateName){
        try {
            Template template = cfg.getTemplate(templateName);
            return template;
        } catch (Exception e) {
            log.error("獲取模板失敗 {}",templateName,e);
            return null;
        }
    }

    /**
     * 獲取模板寫入后的內(nèi)容
     *
     * @param templateName
     * @param model
     * @return
     */
    public static Optional<String> getTplText(String templateName, Map<String, Object> model){
        try {
            Template template = cfg.getTemplate(templateName);
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
            return Optional.ofNullable(text);
        } catch (Exception e) {
            log.error("獲取模板內(nèi)容失敗 {}",templateName,e);
            return Optional.empty();
        }
    }


}
  • 定義模板,如下所示(下面知識一個示意):
<#list list as item>
    ${item.url} | ${item.name} | ${item.age}
</#list>
  • 使用模板并且返回渲染后的字符串,最終返回字符串。
Map<String, Object> model = new HashMap<>();
model.put("list", new ArrayList())
FreeMarkerUtils.getTplText("a.html", model);

問題總結(jié)

  • 我們使用模板的方式可以減少字符串的拼接,提高代碼的可維護性。
  • 如果我們系統(tǒng)中代碼風(fēng)格比較統(tǒng)一,我們可以通過這種方式來生成代碼(只需要對數(shù)據(jù)庫的 table meta 進行讀取,然后再定義 Java 代碼模板即可)。

到此這篇關(guān)于在Java中FreeMarker 模板來定義字符串模板的文章就介紹到這了,更多相關(guān)FreeMarker 定義字符串內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論