zoukankan      html  css  js  c++  java
  • PlayFramework 1 自定义标签 -- FastTags http://unmi.cc/category/javajee/playframework/

    最早是用 HTML 来自定义标签,现在觉得 HTML 写有关逻辑的代码就有点不伦不类了,HTML 里着重是显示代码。前有一篇  PlayFramework 1 模板应用 -- Java 对象扩展 学习了对 Java 对象扩展的方式,如果不是基于已有对象类型进行方法扩展来进行调用,就可以自定义 FastTags 的方式。

    Java 对象扩展的使用是 ${obj.abc()}, FastTags 标签是 #{abc}...${/abc}。

    FastTags 标签类继承自 play.templates.FastTags ,标签对应方法的原型是

    public static void _tagName(Map<?, ?> args, Closure body, PrintWriter out,     ExecutableTemplate template, int fromLine)

    这些都是得益约定优于配置,下面来几个例子,分别说明默认参数,命名参数,及多参数,标签体的处理。

    package utilities;
    
    import groovy.lang.Closure;
    
    import java.io.PrintWriter;
    import java.util.Map;
    
    import play.templates.FastTags;
    import play.templates.GroovyTemplate.ExecutableTemplate;
    import play.templates.JavaExtensions;
    
    public class PlayTags 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 'Yanbin'}Good Morning#{/hello} 
    #{hello arg:'Yanbin'}Good Morning#{/hello}

    多个参数时

    本文原始链接 http://unmi.cc/playframework-1-custom-tag-fast-tags/ , 来自隔叶黄莺 Unmi Blog

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

    页面中写成,用逗号分隔

    #{hello name:'Yanbin', greeting:'Good Morning'/}

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

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

    #{hello 'Yanbin', greeting:'Good Morning'/}

    没指定名字的参数名是 arg。

    最后,无论是在自定义标签还是在扩展的 Java 对象方法中都可以直接使用 request, params, flash, session, play, messages, errors, lang, out 对象,见 Implicit objects available in a template 。

  • 相关阅读:
    threadlocal 变量 跟synchronized 关键字的关系
    Android媒体扫描详细解析之一(MediaScanner & MediaProvider)
    创建视图全文搜索[完整版]
    海量小文件问题综述
    内存拷贝探究
    case功能菜单选项
    linux case ${variable} in
    attack source code
    ftps加密服务器
    vim编程设置
  • 原文地址:https://www.cnblogs.com/zhiji6/p/4444829.html
Copyright © 2011-2022 走看看