如何在ftl中使用宏

时间:2012-02-16 12:31:32

标签: freemarker

我在实现ftl中的宏和函数时充满了困惑。 任何人都可以添加一些有用的信息。

  and what is the difference between macro and function in ftl

由于

2 个答案:

答案 0 :(得分:4)

宏和函数之间的区别:宏通常用于生成标记(或其他长文本)以及流控制和副作用。函数用于计算其他类型的值,包括短纯文本,通常没有副作用。这些都反映在宏没有返回值的事实上,它们只是直接打印到输出。此外,宏的输出不会被#escape转义。这也是为什么它们看起来与HTML标签类似,而${myFunction()}却没有。

除此之外,你有什么困惑?我假设您已找到FreeMarker手册。

答案 1 :(得分:0)

下面是在FTL中使用宏的答案:)

Input-smooks.Json:

 { 
        "title": "Payment Received", 
        "firstName": "vijay", 
        "lastName": "dwivedi", 
        "accountId": "123", 
        "paymentId": "456", 
        "accounts": [ 
            { 
                "accountId": "1111", 
                "paymentId": "1112" 
            }, 
            { 
                "accountId": "2111", 
                "paymentId": "2112" 
            }, 
            { 
                "accountId": "3111",
                "paymentId": "3112" 
            } 
        ] 
    }

Smook-config.xml文件:

一次定义宏,并在需要时用作函数

<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
    xmlns:json="http://www.milyn.org/xsd/smooks/json-1.1.xsd" xmlns:ftl="http://www.milyn.org/xsd/smooks/freemarker-1.1.xsd">

    <params>
        <param name="stream.filter.type">SAX</param>
        <param name="default.serialization.on">false</param>
    </params>

    <json:reader rootName="json" keyWhitspaceReplacement="_">
        <json:keyMap>
            <json:key from="date&amp;time" to="date_and_time" />
        </json:keyMap>
    </json:reader>

    <resource-config selector="json">
        <resource>org.milyn.delivery.DomModelCreator</resource>
    </resource-config>

    <ftl:freemarker applyOnElement="json">
        <ftl:template>
            <!-- 
            <#macro PopulateTasks task_list>
                <#list task_list as att1>
                    "accountId": "${att1.accountId}"
                    "paymentId": "${att1.paymentId}"
                </#list>
            </#macro>

            <@PopulateTasks json.accounts.element/>

             -->
        </ftl:template>
    </ftl:freemarker>

</smooks-resource-list>



  public static void main(String[] args) throws SmooksException, IOException, SAXException {

        long start = System.currentTimeMillis();
        Smooks smooks = new Smooks("src/main/resources/smooks-config.xml");

        try {
            smooks.filterSource(new StreamSource(new 
            FileInputStream("src/main/resources/input_smooks.json")), new 
            StreamResult(System.out));

        } finally {
            smooks.close();
        }
    }

<@PopulateTasks json.accounts.element/>这是调用宏的方法

相关问题