freemarker 入门语法

发布时间 2023-07-20 16:13:26作者: zno2

https://freemarker.apache.org/docs/index.html

 

程序员开胃菜

https://freemarker.apache.org/docs/pgui.html

 

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

public class HelloFreemarker {

    public static void main(String[] args) throws IOException, TemplateException {
        
        // 第一步 Create a configuration instance
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
        cfg.setDirectoryForTemplateLoading(new File("D://"));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);
        cfg.setWrapUncheckedExceptions(true);
        cfg.setFallbackOnNullLoopVariable(false);
        
        // 第二步 Create a data-model
        Map<String, Object> root = new HashMap<>();
        root.put("user", "Big Joe");
        
        // 第三步 Get the template
        Template temp = cfg.getTemplate("test.ftlh");
        
        // 第四步 Merging the template with the data-model
        Writer out = new OutputStreamWriter(System.out);
        temp.process(root, out);
    }
}

 

 

 

 模板路径D://test.ftlh ,模板文件名test.ftlh

 

 

${somedata}

 

${some.data}

 

<#list items as item>
${item}
</#list>

 

<#if somedata?exists>
</#if>

 

移除后四位并把首字母大写

${somedata?substring(0,somedata?length-4)?cap_first}

 

嵌套循环

<#list items as item>
    <#list item as citem>
        ${citem}
     </#list>
<#/list>

 

循环,字符串切割,值等,key存在 

		<#list data.items as item>
			${item.name?split(",")[0]}
			${item.name?split(",")[1]}
			<#if item.type == 'date'>aaaaa</#if>
			<#if item.child?exists>bbbbb</#if>
		</#list>

 

循环map

        Map<String, Object> root = new HashMap<>();
        HashMap<String, String> map = new HashMap<String,String>();
        map.put("name", "小明");
        map.put("age","12");
        root.put("userMap", map);
<#list userMap?keys as key>
${key}:${userMap[key]}
</#list>

 

赋值

<#assign foo = true>
${foo?then('Y', 'N')}

 

语法列表

《使用手册》

https://freemarker.apache.org/docs/ref.html

内置函数 ?调用 (举例:${"foo"?cap_first}

模板命令<# ...> 调用(举例:<#list ['a','b'] as name>)

归类