freemarker

package com.example.tag;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
@Component
public class MyTagDirective implements TemplateDirectiveModel{
    

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        String name = params.get("name").toString();
        System.out.println("自定義標籤參數:" + name);
        // 此處的myTag就是返回給前端的數據
        Writer out = env.getOut();
        if (body != null) {
            // System.out.println(env.getOut().toString()); 獲取標籤中的內容
            //往標籤中寫入內容
            out.write("aaaaa");

            List userlist = new ArrayList();
            userlist.add("a");
            userlist.add("b");
            userlist.add("c");
            env.setVariable("userlist", getBeansWrapper().wrap(userlist));
            
            /**
            * <@myTag name="張三">
            <!-- <#if userlist?? && userlist?size gt 0>
                    <#list userlist as l>
                        <a href="">${l}</a>
                    </#list>
                </#if> -->
            </@myTag>
             */

            body.render(out);
        }
    }
    
    public static BeansWrapper getBeansWrapper() {
        BeansWrapper beansWrapper = new BeansWrapperBuilder(Configuration.VERSION_2_3_21).build();
        return beansWrapper;
    }

}
package com.example.config;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import com.example.tag.MyTagDirective;
import com.example.tag.TreeTagDirective;
@Configuration
public class FreeMarkerConfig {
    @Autowired
    protected freemarker.template.Configuration configuration;
    @Autowired
    private MyTagDirective myTagDirective;
    @Autowired
    private TreeTagDirective treeTagDirective;

    /**
               * 添加自定義標籤
     */
    @PostConstruct
    public void setSharedVariable() {
        try {
             configuration.setSharedVariable("treeTag", treeTagDirective);
             configuration.setSharedVariable("myTag", myTagDirective);
           
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 1.遍歷前端

<#list animals as being><br> 
   <li>${being.name} for ${being.price} Euros<br> 
<#list>
java

相關文章
相關標籤/搜索