google closure 笔记-SOY template
一 使用js模板
closure template 目前支持Java和js。但是模板语法的设计不依赖于任何现成的语言,所以理论上可以支持任何语言,只是暂时只有java编译器。
使用js模板:编写模板文件 .soy文件,然后用一个java编写的编译器将其编译为js文件,这个编译好的js文件会提供一个函数来输出模板内容,
只需要引入这个js文件然后在js中调用这个函数就可以得到模板的内容(内容是一个字符串)。
1, 下载工具包
http://closure-templates.googlecode.com/files/closure-templates-for-javascript-latest.zip
解压之后会得到两个文件:
SoyToJsSrcCompiler.jar, java编写的编译器,可以把soy模板编译为js文件
soyutils.js,编译器编译模板时需要使用的工具类。
2 模板语法
一个完整的模板hello.soy 源码如下
- 1 {namespace demo.hello}
- 2 /**
- 3 * Says hello to the world.
- 4 */
- 5 {template .helloWorld}
- 6 Hello world!
- 7 {/template}
第一行是声明命名空间
第二行是注释,注意,这个注释必须得加,不然编译器会报错
第5行是模板名,是相对于demo.hello命名空间的,即为demo.hello.helloWorld
第6行是输出的内容
第7行是闭合标签
3 编译模板
SoyToJsSrcCompiler.jar可以将soy文件编译为js文件,编译器的使用如下
java -jar ../SoyToJsSrcCompiler.jar --outputPathFormat hello.js hello.soy
编译好的js文件会生成一个全局变量: demo.hello.helloWorld 函数,这个函数返回一个字符串 就是编译好的模板的内容。
使用此模板时只需要document.write(demo.hello.helloWorld())即可。
4 使用模板
新建一个hello.html,内容如下
- 1 <html>
- 2 <head>
- 3 <title>The Hello World of Closure Templates</title>
- 4 <script type="text/javascript" src="../soyutils.js"></script>
- 5 <script type="text/javascript" src="hello.js"></script>
- 6 </head>
- 7 <body>
- 8 <script type="text/javascript">
- 9 // Exercise the .helloWorld template
- 10 document.write(demo.hello.helloWorld());
- 11 </script>
- 12 </body>
- 13 </html>
其中:
第3,4行分别引入了工具类和编译好的模板文件,注意一定要先引入soyutils.js文件
第10行使用了模板hello.js提供的一个函数 demo.hello.helloWorld
5 添加另一个模板
在上述的hello.soy文件后追加如下代码
- 9 /**
- 10 * Greets a person using "Hello" by default.
- 11 * @param name The name of the person.
- 12 * @param? greetingWord Optional greeting word to use instead of "Hello".
- 13 */
- 14 {template .helloName}
- 15 {if not $greetingWord}
- 16 Hello {$name}!
- 17 {else}
- 18 {$greetingWord} {$name}!
- 19 {/if}
- 20 {/template}
这个新加的模板中使用了两个变量name和greetingWord。
编译此模板后生成的hello.js代码如下
- 1 // This file was automatically generated from hello.soy.
- 2 // Please don't edit this file by hand.
- 3
- 4 if (typeof demo == 'undefined') { var demo = {}; }
- 5 if (typeof demo.hello == 'undefined') { demo.hello = {}; }
- 6
- 7
- 8 demo.hello.helloWorld = function(opt_data, opt_sb) {
- 9 var output = opt_sb || new soy.StringBuilder();
- 10 output.append('Hello world!');
- 11 return opt_sb ? '' : output.toString();
- 12 };
- 13
- 14
- 15 demo.hello.helloName = function(opt_data, opt_sb) {
- 16 var output = opt_sb || new soy.StringBuilder();
- 17 output.append((! opt_data.greetingWord) ? 'Hello ' + soy.$$escapeHtml(opt_data.name) + '!' : soy.$$escapeHtml(opt_data.greetingWord) + ' ' + soy.$$escapeHtml(opt_data.name) + '!');
- 18 return opt_sb ? '' : output.toString();
- 19 };
可以看到其中生成了两个函数helloWorld和helloName
传递参数的方式很简单,只需要在调用的时候把参数以key-value的形式传入即可
- 1 <html>
- 2 <head>
- 3 <title>The Hello World of Closure Templates</title>
- 4 <script type="text/javascript" src="../soyutils.js"></script>
- 5 <script type="text/javascript" src="hello.js"></script>
- 6 </head>
- 7 <body>
- 8 <script type="text/javascript">
- 9 // Exercise the .helloWorld template
- 10 document.write(demo.hello.helloWorld());
- 11 document.write("<br />" + demo.hello.helloName({name:"bob"})); //传递参数
- 12 document.write("<br />" + demo.hello.helloName({greetingWord:"wellcome:" ,name:"Lily"})); //传递两个参数
- 13 </script>
- 14 </body>
- 15 </html>
二 使用java模板
编写模板的规则都是一样的,依然按上面描述的方法来编写一个soy文件,不同之处是:
js模板需要用一个编译器编译为js文件,而java模板则直接在servlet中创建一个对象,这个对象可以将soy文件编译为字符串。
下载工具包:
http://closure-templates.googlecode.com/files/closure-templates-for-java-latest.zip
新建HelloWorld.java文件:
- 1 import com.google.template.soy.SoyFileSet;
- 2 import com.google.template.soy.data.SoyListData;
- 3 import com.google.template.soy.data.SoyMapData;
- 4 import com.google.template.soy.tofu.SoyTofu;
- 5
- 6 import java.io.File;
- 7
- 8 public class HelloWorld {
- 9
- 10 public static void main (String[] args) {
- 11
- 12 // Bundle the Soy files for your project into a SoyFileSet.
- 13 SoyFileSet sfs = new SoyFileSet.Builder().add(new File("demo/hello.soy")).build();
- 14
- 15 // Compile the template into a SoyTofu object.
- 16 // SoyTofu's newRenderer method returns an object that can render any template in file set.
- 17 SoyTofu tofu = sfs.compileToJavaObj();
- 18
- 19 // Call the template with no data.
- 20 System.out.println(tofu.newRenderer("demo.hello.helloWorld").render());
- 21 System.out.println(tofu.newRenderer("demo.hello.helloName")
- 22 .setData(new SoyMapData(
- 23 "name", "Ana",
- 24 "additionalNames")
- 25 ).render());
- 26 }
- 27 }
然后编译运行代码:
javac -classpath soy-latest.jar HelloWorld.java
java -classpath soy-latest.jar HelloWorld
结果总是出错,不知道为什么⋯⋯
三 模板语法
语句:
模板中语句分为两类,html语句和模板语句,所有的模板语句都包括在{}中。一般语法如下:
{command value}
如果省略command,则默认为print
变量:
变量以$符号开头:
{$name}
引用类型的数据,其输出方式类似于js,
$a.0.c == $a[0].c == $a[0]["c"]
因为模板会自动删除多余空格,所以可以用{sp}或者{nil}来添加空格
在namespace声明中可以指定escape
{namespace ns autoescape="contextual"}
模板支持的变量类型如下
|
Type |
Literal |
|
Null |
null |
|
Boolean |
false or true |
|
Integer |
Decimal (e.g. -827) or hexadecimal (must begin with 0x and must use capital A-F, e.g. 0x1A2B). |
|
Float |
Must be in decimal and must either:
Note: Even though the primitive type is named Float, it has the precision of a number in JavaScript or a double in Java. |
|
String |
Delimited by single quotes only. Closure Templates support these escape sequences: \\, \', \", \n, \r, \t, \b, \f, and \u#### where the #### can be any 4 hex digits to denote a Unicode code point. |
|
List |
A comma-separated list of heterogeneous values, for example: [1, 'two', [3, 'four']]. [] is the empty list. |
|
Map |
['key': 'value', <keyExpr>: <valueExpr>] maps keys to values. Square brackets ([…]) delimit both lists and maps because braces ({…}) delimit commands. |
运算符
- - (unary) not
- * / %
- + - (binary)
- < ]]]]> <= >=
- == !=
- and
- or
- ?: (ternary)
函数:
模板提供的基本函数如下:
|
Function |
Usage |
|
isFirst($var) |
Use this with the foreach command. For more information see the foreach section of the Commands chapter. |
|
isLast($var) |
Use this with the foreach command. See more information in the foreach section of the Commands chapter. |
|
index($var) |
Use this with the foreach command. See more information in the foreach section of the Commands chapter. |
|
hasData() |
Checks whether a template data object was passed to this template. This function is rarely needed — use it only if all parameters to a template are optional, and thus the template may be called without any data object at all (omitted or null in javascript or null in Java). In this situation, the correct way to check for the presence of a parameter is {if hasData() and $myParam}. Alternatively, if you choose to always pass an empty data map (i.e. never pass null) to your template even when none of the optional params are needed, then you never have to use the hasData() function. |
|
length($list) |
The length of a list. |
|
keys($map) |
The keys in a map as a list. There is no guarantee on order. |
|
round(number) |
Round to an integer. |
|
round(number, numDigitsAfterDecimalPoint) |
If numDigitsAfterDecimalPoint is positive, round to that number of decimal places; if numDigitsAfterDecimalPoint is negative, round to an integer with that many 0s at the end. |
|
floor(number) |
The floor of the number. |
|
ceiling(number) |
The ceiling of the number. |
|
min(number, number) |
The min of the two numbers. |
|
max(number, number) |
The max of the two numbers. |
|
randomInt(rangeArg) |
A random integer in the range [0, rangeArg - 1] (where rangeArg must be a positive integer). |
注释:
- // begins a rest-of-line comment
- /* comment */ delimit an arbitrary comment (can be multiline)
详细语法:见:https://developers.google.com/closure/templates/docs/commands
google closure 笔记-SOY template的更多相关文章
- First Adventures in Google Closure -摘自网络
Contents Introduction Background Hello Closure World Dependency Management Making an AJAX call with ...
- 使用Google Closure Compiler高级压缩Javascript代码注意的几个地方
介绍 GCC(Google Closure Compiler)是由谷歌发布的Js代码压缩编译工具.它可以做到分析Js的代码,移除不需要的代码(dead code),并且去重写它,最后再进行压缩. 三种 ...
- 主流JavaScript框架(Dojo、Google Closure、jQuery、Prototype、Mootools和YUI)的分析和对比
本文主要选取了目前比较流行的JavaScript框架Dojo.Google Closure.jQuery.Prototype.Mootools和YUI进行对比,主要是根据网上的资料整理而成,希望可以供 ...
- Google Closure Compiler高级压缩混淆Javascript代码
一.背景 前端开发中,特别是移动端,Javascript代码压缩已经成为上线必备条件. 如今主流的Js代码压缩工具主要有: 1)Uglify http://lisperator.net/uglifyj ...
- JavaScript代码压缩工具UglifyJS和Google Closure Compiler的基本用法
网上搜索了,目前主流的Js代码压缩工具主要有Uglify.YUI Compressor.Google Closure Compiler,简单试用了UglifyJS 和Google Closure Co ...
- Google Closure Compiler 高级模式及更多思考(转)
前言 Google Closure Compiler 是 Google Closure Tools 的一员,在 2009 年底被 Google 释出,早先,有 玉伯 的 Closure Compile ...
- 使用Google Closure Compiler全力压缩代码(转)
JavaScript压缩代码的重要性不言而喻,如今的压缩工具也有不少,例如YUI Compressor,Google Closure Compiler,以及现在比较红火的UglifyJS.Uglify ...
- 使用Google Closure Compiler高级压缩Javascript代码
背景 前端开发中,特别是移动端,Javascript代码压缩已经成为上线必备条件. 如今主流的Js代码压缩工具主要有: 1)Uglify http://lisperator.net/uglifyjs/ ...
- Google Play笔记之上架
我最近负责Google Play上架的主要工作 ,现已进入开放测试阶段(随后就可全球首发~~).接入工作已完成,这篇记录一下上架后期的笔记. 开放测试 开放测试是指对所有玩家进行开放式测试,玩家可以通 ...
随机推荐
- PHP + webuploader 视频上传
上传方式,PHP默认方式 和 FTP 上传 1.修改PHP 配置: php.ini 修改以下配置项为适合的数据 php中 php.ini 文件修改 file_uploads = On //允许文件上 ...
- Docker(九)-Docker创建Selenium容器
SeleniumHQ官方项目:https://github.com/seleniumHQ/docker-selenium 项目目前快速迭代中. Selenium 这里主要针对的是 Selenium G ...
- google-gson 使用及GsonBuilder设置
Json是一种类似于XML的通用数据交换格式,具有比XML更高的传输效率. 从结构上看,所有的数据(data)最终都可以分解成三种类型: 第一种类型是标量(scalar),也就是一个单独的字符串( ...
- js中的async await
JavaScript 中的 async/await 是属于比较新的知识,在ES7中被提案在列,然而我们强大的babel粑粑已经对它进行列支持! 如果开发中使用了babel转码,那么就放心大胆的用吧. ...
- 04 Spring的@Autowired注解、@Resource注解、@Service注解
什么是注解 传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事务,这么做有两个缺点: 1.如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大:如果按需求分 ...
- 【字符串算法1】 再谈字符串Hash(优雅的暴力)
[字符串算法1] 字符串Hash(优雅的暴力) [字符串算法2]Manacher算法 [字符串算法3]KMP算法 这里将讲述 [字符串算法1] 字符串Hash 老版原文: RK哈希(Rabin_Ka ...
- 面试题:get和post的本质区别
前言:相信小伙伴们面试时候一定都遇到过这个问题,即使没有遇到过,至少也听说过,网上资料一大片,大概每个人都能说出来一些.但是总感觉面试装逼不成功,所以就翻阅了部分资料,进一步整理了下. 一般当我们提到 ...
- 洛谷P1155 双栈排序
这题什么毒瘤......之前看一直没思路,然后心说写个暴搜看能有多少分,然后就A了??! 题意:给你一个n排列,求它们能不能通过双栈来完成排序.如果能输出最小字典序方案. [update]这里面加了一 ...
- 【CF61D】Eternal Victory
题目大意:给定一棵 N 个节点的树,求从 1 号节点(根节点)出发,任意节点结束,且至少经过每个节点一次的最短路径是多少. 题解:首先考虑最终要回到根节点的情况,可以发现最短路径长度一定等于该树边权的 ...
- word 公式为图片