• Play Framework 的模板引擎


    Play 框架有自己的模板引擎来生成HTML页面,该引擎使用 Groovy 做为表达式语言。你可以直接使用 Groovy 语言来创建动态的网页,但并无需学习 Groovy 所有的知识,你需要了解的只是跟 Java 非常相近的一部分。Play 将所有的模板文件都放在 app/views 目录下,所有页面都是在请求时即时解析的。

    接下来我们创建一个简单应用:

    oschina@oschina.net:~/dev/play$ /usr/share/play/play new views
    ~        _            _
    ~  _ __ | | __ _ _  _| |
    ~ | '_ \| |/ _' | || |_|
    ~ |  __/|_|\____|\__ (_)
    ~ |_|            |__/
    ~
    ~ play! 1.0.3, http://www.playframework.org
    ~
    ~ The new application will be created in /home/wichtounet/dev/play/views
    ~ What is the application name? Views
    ~
    ~ OK, the application is created.
    ~ Start it with : play run views
    ~ Have fun!
    ~

    接下来检查生成的文件,进入 app/views 目录,我们可以看到下面这些内容:

    • Application : 存放应用主 controller 程序的模板
    • errors : 存放错误页面模板,例如 404、500等
    • main.html : 主页面模板

    打开  Application/index.html ,代码如下:

    #{extends 'main.html' /}
    #{set title:'Home' /}
     
    #{welcome /}

    第一行表明此模板扩展自 main.html,接下来使用了 Play 框架的 set 指令来设置页面的标题,这些指令都要进行关闭,最后一行打印一行欢迎信息。

    然后我们再来看看 main.html 模板:

    <!DOCTYPE html>
     
    <html>
        <head>
            <title>#{get 'title' /}</title>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
            <link rel="stylesheet" type="text/css" media="screen" href="@{'/public/stylesheets/main.css'}">
            #{get 'moreStyles' /}
            <link rel="shortcut icon" type="image/png" href="@{'/public/images/favicon.png'}">
            <script src="@{'/public/javascripts/jquery-1.4.2.min.js'}" type="text/javascript" charset="utf-8"></script>
            #{get 'moreScripts' /}
        </head>
        <body>
            #{doLayout /}
        </body>
    </html>

    这个模板中包含一些特殊的指令:

    • #{get ‘title’ /} : 获取变量 title 的值,该值仅在模板页面中有效
    • @{‘/public/stylesheets/main.css’} : 引入某个静态资源
    • #{doLayout /} : 此处插入子模板的内容,在本例中就是前面提到的 index.html 页面,index.html 扩展自 main.html

    如何在模板间传递参数呢?

    传递参数很重要,例如我们在 controller 中读取一些数据,并将这些数据传递到 view 中进行显示。在 Play 框架中可以使用 render 方法来处理,例如:

    package controllers;
     
    import play.mvc.*;
     
    public class Application extends Controller {
        public static void index() {
            String hello = "Hello World from Controller !";
     
            render(hello);
        }
    }

    index 方法中向模板传递了一个名为 hello 的变量,要在模板中获取这个变量的值,只需 ${hello} 即可:

    #{extends 'main.html' /}
    #{set title:'Home' /}
     
    Hello from the view
    <br />
    ${hello}

    怎样,很简单吧?

    来个更复杂点的类吧

    package models;
     
    public class Book {
        private final String title;
     
        public Book(String title) {
            super();
     
            this.title = title;
        }
     
        public String getTitle() {
            return title;
        }
    }

    然后在 controller 传递此类的实例:

    public static void index() {
        Book book = new Book("Hello Play !");
        render(book);
    }

    接下来在模板中获取该对象

    #{extends 'main.html' /}
    #{set title:'Home' /}
     
    Hello from the view
    <br />
    I've a book for you "${book.title}".

    这里使用了 JavaBean 的 getting 方法,因此我们的Bean 必须有 getTitle 方法。

    所有动态内容的输出,Play 框架都做了转码处理,以防止XSS跨站点攻击,如果你不想这样做,那么可使用 raw() 方法,例如

    ${book.title.raw()}

    但这不是一个好习惯,仅在你确认会带来什么后果时才使用。

    模板的注释方式如下:

    *{Will not be evaluated by the template engine}*

    数组和列表

    在实际使用过程中,列表和数组是经常要用到的,下面是一个传递列表的实例:

    public static void index() {
            List<Book> books = new ArrayList<Book>(3);
            books.add(new Book("Hello Play !"));
            books.add(new Book("Hello Template !"));
            books.add(new Book("Hello Engine !"));
            render(books);
    }

    模板中使用该列表对象的代码如下:

    #{extends 'main.html' /}
    #{set title:'Home' /}
    I've some books for your :
    <ul>
        #{list items:books, as:'book'}
            <li>${book.title}</li>
        #{/list}
    </ul>

    不是很复杂吧:)

    使用脚本

    如果你需要做更复杂的操作,我们可以在 Groovy 中使用脚本,在脚本中可以定义变量并可直接使用其他变量,例如:

    #{extends 'main.html' /}
    #{set title:'Home' /}
    I've some books for your :
    <ul>
        #{list items:books, as:'book'}
            %{
               bookTitle = book.title.toUpperCase();
            }%
            <li>${bookTitle}</li>
        #{/list}
    </ul>

    你可以做包括迭代、条件等一大堆复杂的事情,但记住,不要在模板中做过于复杂的功能,将这些业务逻辑放在 controller 或者是 models 中,模板应该越简单越好。

    定义标签

    Play 框架自带很多的标签,但你可以自己创建一些,为了创建标签,我们必须在views目录下创建名为 tags的子目录,例如我们创建一个 booklist.html 文件,存放在 views/tags 目录下,booklist.html 的代码如下:

    <ul>
        #{list items:_items, as:'book'}
            %{
                bookTitle = book.title.toUpperCase();
            }%
            <li>${bookTitle}</li>
        #{/list}
    </ul>

    使用 '_' 来获取参数,本例中是 _items

    有了这个自定义的tag,我们就可以将上面那个模板修改为:

    #{extends 'main.html' /}
    #{set title:'Home' /}
    I've some books for your : 
    #{booklist items:books /}

    尽量利用参数来使得 tag 更加灵活。

    到此我们就介绍了 Play 模板的一些基本的要素,更多关于Play 框架的模板请看官方文档

  • 相关阅读:
    Request.QueryString("id")与Request("id")区别
    C#中System.DateTime.Now.ToString()用法
    MySQL忘记密码
    zookeeper不停的拒绝client连接
    【异常】 Ensure that config phoenix.schema.isNamespaceMappingEnabled is consistent on client and server.
    kafka无法消费数据提示找不到分区
    yum list报一些error的组件
    【异常】‘for’ loop initial declarations are only allowed in C99 mode
    Airflow安装异常:ERROR: flask-appbuilder 1.12.3 has requirement Flask<2,>=0.12, but you'll have flask 0.11.1 which is incompatible.
    批量kill指定名称的进程
  • 原文地址:https://www.cnblogs.com/ibook360/p/2311829.html
Copyright © 2020-2023  润新知