代码改变世界

webit-script初体验

2014-10-21 20:27  radray  阅读(349)  评论(0编辑  收藏  举报
 1 package webitscript.template.radray.com;
 2 
 3 import webit.script.Engine;
 4 import webit.script.Template;
 5 import webit.script.exceptions.ResourceNotFoundException;
 6 
 7 import java.io.*;
 8 import java.util.HashMap;
 9 import java.util.Map;
10 
11 /**
12  * Created by ray on 14-10-21.
13  */
14 public class HelloWorld {
15     public static String Hello() {
16         String result = "";
17         Engine engine = Engine.create("", null);
18         Map<String, Object> map = new HashMap<String, Object>();
19         map.put("a1", "world");
20         StringWriter writer = new StringWriter();
21         Template template = null;
22         try {
23             template = engine.getTemplate("/test/webitscript/template/radray/com/1.html");
24             template.merge(map, writer);
25             result = writer.toString();
26         } catch (ResourceNotFoundException e) {
27             e.printStackTrace();
28         }
29         return result;
30     }
31 }
1 hello <%var a1;echo a1;%>
 1 package test.webitscript.template.radray.com;
 2 
 3 import junit.framework.Assert;
 4 import org.junit.Test;
 5 import webitscript.template.radray.com.HelloWorld;
 6 
 7 /**
 8  * Created by ray on 14-10-21.
 9  */
10 public class TestHelloWorld {
11     @Test
12     public void TestHelloMethod() {
13         Assert.assertEquals(HelloWorld.Hello(), "hello world");
14     }
15 }

在使用时,需注意:

一、engine.getTemplate方法中的模板路径,是基于classpath来获取的,你可以在配置文件中自定义跟路径,但不可以直接使用绝对路径;

二、在模板代码中,默认情况,你需要先声明变量,再进行使用,即便你已经将该名称的object put进map中;

三、即使只有一个表达式,也不要忘了加封号

 

示例下载:链接: http://pan.baidu.com/s/1hq03AqK 密码: pef0

2014-10-21 20:26:48

-------------------------------------------------------------------------------------------------------------------

关于webit-script

介绍:
 
源代码:

github: https://github.com/zqq90/webit-script

 
第一作者:webit(QQ:812070996)
兴趣小组:42710106
专业小组:302505483