velocity使用中遇到的問題

減法運算
       #set($page=$page-1)      ##這條語句會出錯,改成如下:
       #set($page=$page- 1)    ##在減號前後各加一個空格

在做分頁處理的時候,這個地方老報錯,我快暈倒了,最後終於找到了問題,希望使用velocity的同仁看到後,能更好的使用了。

 

 

判斷字符是否相等
       #if($a==$b) <div>success</div>#end     ##如果$a或$b爲空,這條語句有語法錯誤,改成如下:
       #if("$a"=="$b") <div>success</div>#end 或者
       #if($a&&$b&$a==$b) <div>success</div>#end

javascript中使用vm變量
        <script>
         #if($a&&$a.length()>0)
            var a="$a"
            alert(a);
        #end
        </script>

foreach循環的counter(循環次數計數)
        在velocity.properties中有一段配置
        directive.foreach.counter.name = velocityCount               ##定義變量名稱
        directive.foreach.counter.initial.value = 1                          ##定義計算從1開始累加
$velocityCount

 

模板的解析
    1.模板文件的merge
        StringWriter writer = new StringWriter();
        Map context=new HashMap();
        context.put("vm_prop1","12");
       VelocityContext model = new VelocityContext(context);
       model.put("vm_prop2", "14");
   
        try {
             Template tpl = Velocity.getTemplate("portal.vm");
            tpl.merge(model, writer);
            writer.close();
        } catch (Exception e) {
             log.error("Can't merge portal.vm", e);
         }
        log.info(writer.toString);

        對portal.vm中的vm_prop1和vm_prop2兩個變量賦值並解析返回writer

    2.字符串的merge    
      public static boolean evaluate(org.apache.velocity.context.Context context, Writer writer, String logTag, Reader reader) throws ParseErrorException, MethodInvocationException, ResourceNotFoundException, IOException {
        SimpleNode nodeTree = null;
        try {
              nodeTree = RuntimeSingleton.parse(reader, logTag, false);
        } catch (ParseException pex) {
              throw new ParseErrorException(pex.getMessage());
        }
        if (nodeTree != null) {
              InternalContextAdapterImpl ica = new InternalContextAdapterImpl(context);
              ica.pushCurrentTemplateName(logTag);
        try {
            try {
                 nodeTree.init(ica, RuntimeSingleton.getRuntimeServices());
            } catch (Exception e) {
                 RuntimeSingleton.error("Velocity.evaluate() : init exception for tag = " + logTag + " : " + e);
            }
            nodeTree.render(ica, writer);
        } finally {
            ica.popCurrentTemplateName();
         }

    return true;
   }
   return false;
}


StringReader reader = new StringReader("#foreach($n in $list) <ul><li>$n.Id</li></ul>#end");
reader爲讀取一個vm文件裏的內容,包含vm表達式,logTag爲這一串字符串賦予一個模板名稱(如:"a.vm")通過context對vm表達式賦值,並對reader讀取的字符串進行解析,返回給writer

servlet應用
    1.可增加一個Listener,在這個Listener初始化velocity的一些配置,這樣避免每個servlet都需要初始化velocity

          Properties props = new Properties();
         try {
             File conf = new File(event.getServletContext().getRealPath("WEB-INF/velocity.properties"));
             props.load(new FileInputStream(conf));
         }catch (Exception e) {
             e.printStackTrace();
         }
         try {
             Iterator<Object> iter = props.keySet().iterator();
             while(iter.hasNext()) {
                 String key = (String) iter.next();
                 Velocity.setProperty(key,props.getProperty(key));
             }
             Velocity.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
                 "org.apache.velocity.runtime.log.SimpleLog4JLogSystem" );
             Velocity.setProperty("runtime.log.logsystem.log4j.category", "sys.velocity");
             Velocity.setProperty("resource.loader","file");
             Velocity.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, event.getServletContext().getRealPath("/WEB-INF/templates"));
             Velocity.setProperty("parser.pool.size","3");
             Velocity.setProperty("velocimacro.library","macro_default.vm,macro_expopo.vm");
             Velocity.init();
         } catch (Exception e) {
             e.printStackTrace();
          }

原文章地址:http://hi.baidu.com/anct125/blog/item/d2c600098f4178236a60fb60.html

發佈了130 篇原創文章 · 獲贊 15 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章