play框架前端学习记录

Play Framework是full-stack的Java Web的应用框架,包括一个简单的无状态MVC,具有Hibernate的对象持续,一个基于Groovy的模板引擎,以及建立一个现代Web应用所需的所有东西,它的目标是让基于Java的web应用开发变得更加容易。

前端使用最多的是它高效的模板引擎

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
 
<c:choose>
    <c:when test="${emails.unread != null && fn:size(emails.unread)}">
        You have ${fn:size(emails.unread)} unread email(s)!
    </c:when>
    <c:otherwise>
        You have no unread emails!
    </c:otherwise>
</c:choose>

通过play之后就非常简短

You have ${emails.unread ?: 'no'} ${emails.unread?.pluralize('email')} !

模板语法
${…}用于输出变量

<h1>Client ${client.name}</h1>

如果不能确定值是否为空可以这样写

<h1>Client ${client?.name}</h1>

#{extends /} and #{doLayout /}
在公共的页面里使用#{doLayout /}包含具体页面,具体的页面里使用#{extends /}来继承公共页面。
如果需要共享变量可以用#{set}设置变量,#{get}获取变量,这个变量是页面和主页面之间共享的变量
具体的页面代码例子

#{extends 'simpledesign.html' /}
 
#{set title:'A decorated page' /}
This content will be decorated.

公共页面代码例子

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>#{get 'title' /}</title>
  <link rel="stylesheet" type="text/css" href="@{'/public/stylesheets/main.css'}" />
</head>
<body>
  <h1>#{get 'title' /}</h1>
  #{doLayout /}
  <div class="footer">Built with the play! framework</div>
</body>
</html>

#{include /}
用来包含页面片段的 ,页面上下文共享

#{include 'wechat/footer.html' /}

#{tagName /}
标签可以用来插入标签,比方说插入script标记来加载javascript文件,但标记必须闭合,上下文不共享

#{script 'jquery.js' /}
/* 或者这样闭合 */
#{script 'jquery.js'}#{/script}

/* 也可以加其它参数 */{script id:'myscript',src:'script.js',charset:'utf-8'/}{stylesheet id:'main',media:'print',src:'print.css'/}

list标签循环
通过list标签迭代任何集合,需要所迭代的集合变量名,如果不as设置item名,会用默认的_作为item变量
例如

<h1>Client ${client.name}</h1>
<ul>
    #{list items:client.accounts, as:'account' }
        <li>${account}</li>
    #{/list}
</ul>

/* 不设置item变量名 */
<ul>
    #{list items:client.accounts}
        <li>${_}</li>
    #{/list}
</ul>

#{if cond}…#{/ if} #{elseif cond}…#{elseif} #{else}…#{/ else}
#{ifnot cond}…#{/ ifnot}
这是条件判断语句,简单粗暴

#{if _?.target == 1}判断成功{/if}
#{else}失败的结果#{/else}
/* 注意_是循环的item的默认参数名,需要辨别 */

自动转义
模板引擎会自动转义所有的动态表达式,避免应用程序中出现的XSS安全问题,所以如果需要不转义的结果可以使用以下方法

/* 默认自动转义 */
${title} /* 结果 &lt;h1&gt;Title&lt;/h1&gt; */

/* 少量文本不需要转义 */
${title.raw()} /* 结果 <h1>Title</h1> */

/* 大量html结果不需要转义 */
#{verbatim}
    ${title}  /* 结果 <h1>Title</h1> */
#{/verbatim}

@{…} or @@{…}
You can use the Router to (reverse) generate a URL corresponding to a specified route. From a template you can use the special @{…} syntax to do that.

<h1>Client ${client.name}</h1>
<p>
   <a href="@{Clients.showAccounts(client.id)}">All accounts</a>
</p>
<hr />
<a href="@{Clients.index()}">Back</a>

∗{ … }∗
用来注释文案

%{…}%
用来运行表达式,可以声明变量或者定义语句,也可以插入脚本

%{
  String fullName = client.name.toUpperCase()+' '+client.forname;
}%
<h1>Client ${fullName}</h1>

实际上play的文档里都有,这些是比较常用的。

猜你喜欢

转载自blog.csdn.net/wzp20092009/article/details/86494197