欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

freemarker标签,指令,自定义标签

程序员文章站 2022-06-08 23:47:56
...

freemarker配置详见
http://blog.csdn.net/fengqingyuebai19/article/details/79378945
简单的来说freemarker能改变html中的${value}中的value,实现网页的动态变化。
freemarker有以下几个定义:

1.ftl标签:就是已<#>开头的那些命令 比如<#if

2.directives 指令 :比如例子中的table

3.自定义标签,新建一个global.ftl 模板, 定义myTag标签,name是入参,hello ${name} 是返回值。然后在application-context.xml中添加freemarkerSettings,配置模板的引用

global.ftl

<#macro myTag name >
hello ${name}
</#macro>

application-context.xml,global.ftl as g以后就用@g.myTag 进行标签的调用

<bean id="freemarkerConfig"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="WEB-INF/" />
        <property name="defaultEncoding" value="UTF-8" />
        <property name="freemarkerSettings">
            <props>
                <prop key="auto_import">/config/ftl/spring.ftl as
                    spring,/config/ftl/global.ftl as g</prop>
            </props>
        </property>
    </bean>

hello.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>hello</title>
</head>
<body>

hello ${book!}

<p>ftl标签:</p>
<#if book== "234">yes, the book is 234</#if>
<#if book!= "234">no, the book is not 234</#if>
<p>指令:</p>
<table border=1>
<tr><th>书名<th>价格
<tr><td>${book}<td>${price!0}
</table>

<p>自定义标签:</p>
<@g.myTag name="Jone"/>

</body>
</html>

HelloWorldController

package com.my.demo.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloWorldController {

    @RequestMapping("hello")
    public String loginFunction(HttpServletRequest request, Model model){
        System.out.println("controller start");
        model.addAttribute("book","123");
        System.out.println("controller end");
        return "hello";
    }

}