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}