1.Closure Templates是幹什麼用的?
它是一個用戶端和伺服器端的模闆系統,用來動态建立可複用的HTML和UI元素。
2.為什麼要使用Closure Templates?
2.1 子產品化------相對于傳統的模闆系統中需要為每個頁面建立一個整體模闆,Closure Templates是子產品/元件化的,你可以從視圖顯示的角度來分解應用程式的邏輯,并建立自己的使用者界面。
2.2 同時适用多個語言--------使用者可以在用戶端和伺服器端适用相同的模闆,模闆中可以使用JS腳本語言或Java。
2.3 在用戶端的高效運作-------Closure Templates會被預編譯成高效的JS腳本,以求最大化用戶端的顯示效果。
2.4 模闆之間可以互相調用。
3.如何建立一個Closure Template并用JS調用?
3.1 下載下傳
closure-templates-for-javascript-latest.zip
這個檔案包括:
SoyToJsSrcCompiler.jar
把Closure Template編譯成高效的腳本。
soyutils.js 腳本代碼會使用到這些工具。
3.2 将上面的檔案放入自己的工作目錄(helloworld_js)裡。
3.3 在工作目錄中建立 sample.soy檔案。(所有包含Closure Templates并以soy字尾結尾的檔案就是soy檔案)
在sample.soy檔案中添加一行 {namespace examples.simple}。這表示了在這個檔案中使用到的模闆的命名空間。
3.4 試着寫第一個模闆的内容,例如:
/**
* Says hello to the world.
*/
{template .helloWorld} 這是模闆名字的一部分,結合前面的命名空間,模闆的全名是:examples.simple.helloWorld
Hello world!
{/template}
3.5 使用指令将模闆編輯成JS腳本:
~/helloworld_js$ java -jar SoyToJsSrcCompiler.jar --outputPathFormat simple.js --srcs simple.soy
這個指令産生的simple.js檔案,通過examples.simple.helloWorld()來渲染模闆内容。
模闆的内容、邏輯會在 .js 檔案中得以展現。
注意:.js 檔案是.soy 自動産生的,不要再去編輯. js 檔案!
3.6 在自己的工作目錄 helloworld_js中,建立一個HTML檔案,内容如下:
<html>
<head>
<title>The Hello World of Closure Templates</title>
<script type="text/javascript" src="soyutils.js"></script>
<script type="text/javascript" src="simple.js"></script>
</head>
<body>
<script type="text/javascript">
// Exercise the .helloWorld template
document.write(examples.simple.helloWorld());
</script>
</body>
</html> soyutils.js"></script>
<script type="text/javascript" src="simple.js"></script>
</head>
<body>
<script type="text/javascript">
// Exercise the .helloWorld template
document.write(examples.simple.helloWorld());
</script>
</body>
</html>
于是就通過JS調用了Closure Template的模闆内容,通路HTML即可看到。
4.如何建立一個Closure Template并用Java調用?
4.1 下載下傳
closure-templates-for-java-latest.zip
.
這其中包括兩個檔案: soy-latest.jar 包含所有closure templates模闆類和依賴;
SoyParseInfoGenerator.jar轉換soy檔案并生成Java類。
4.2 将上面的檔案放入自己的工作目錄。
建立simple.soy檔案,聲明命名空間,輸入模闆内容:
/**
* Says hello to the world.
*/
{template .helloWorld}
Hello world!
{/template}
4.3 在工作目錄中建立一個Java類:HelloWorld.java
public class HelloWorld {
public static void main (String[] args) {
// 在項目中,将soy檔案綁定到 SoyFileSet中。
SoyFileSet sfs = SoyFileSet.builder().add(new File("simple.soy")).build();
// 将soy模闆檔案編譯成 SoyTofu 對象。
// SoyTofu 對象的 newRenderer( )方法傳回的render,可以渲染 SoyFileSet 中任何模闆的内容
SoyTofu tofu = sfs.compileToTofu();
// 渲染模闆内容
System.out.println(tofu.newRenderer("examples.simple.helloWorld").render());
}
}