Play framework使用java代码自定义标签--FastTags

Java自定义标签必须实现play.templates.FastTags类,标签对应的原型是:

public static void _tagName(Map<?, ?> args, Closure body, PrintWriter out, 
   ExecutableTemplate template, int fromLine)
这些都是得益于约定优于配置,下面就举几个例子来看一下标签的用法:

package tags;

import java.io.PrintWriter;
import java.util.Map;

import groovy.lang.Closure;
import play.templates.FastTags;
import play.templates.GroovyTemplate.ExecutableTemplate;
import play.templates.JavaExtensions;


public class PlayTag extends FastTags{

    public static void _hello(Map<?, ?> args, Closure body, PrintWriter out,
               ExecutableTemplate template, int fromLine){
        out.println("Hello"+args.get("arg")+" "+JavaExtensions.toString(body));
    }
}

上面定义了一个hello标签,参数从args中获得,默认参数名是arg;标签题用body获得,在html页面中应用:

#{hello '孙俪'} 开学了#{/hello}
#{hello arg:'孙俪'} 开学了#{/hello}


多个参数时:

    public static void _hello(Map<?, ?> args, Closure body, PrintWriter out,
               ExecutableTemplate template, int fromLine){
        out.println("Hello"+args.get("name")+" "+args.get("date")+" "+JavaExtensions.toString(body));
    }


页面中的参数用逗号隔开:

#{hello name:'孙俪',date:'2017年08月09号'} 开学了#{/hello}


默认参数名和命名参数同时使用:

    public static void _hello(Map<?, ?> args, Closure body, PrintWriter out,
               ExecutableTemplate template, int fromLine){
        out.println("Hello"+args.get("arg")+" "+args.get("date")+" "+JavaExtensions.toString(body));
    }


#{hello '孙俪',date:'2017年08月09号'} 开学了#{/hello}


没指定名字的参数是arg;

最后无论是在自定义标签中还是扩展的java对象中都可以使用内置的request, params, flash, session, play, messages, errors, lang, out 对象;


FastTags标签可以有自己的自定义命名空间,如果为了避免与默认命名空间里的play.templates.FastTags自定义的标签冲突,可以为自己的@FastTags.Namespace标签类加标注:


@FastTags.Namespace("my.tags")
public class PlayTag extends FastTags{

    public static void _hello(Map<?, ?> args, Closure body, PrintWriter out,
               ExecutableTemplate template, int fromLine){
        out.println("Hello"+args.get("arg")+" "+args.get("date")+" "+JavaExtensions.toString(body));
    }
}


这样使用标签就应该是:

#{my.tags.hello '孙俪',date:'2017年08月09号'} 开学了#{/my.tags.hello}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值