티스토리 뷰
== VTL (Velocity Template Language) 문법 ==
=== 간단한 예제 ===
<html>
<body>
#set ($foo = "Velocity")
Hello $foo World!
</body>
<html>
=== 코멘트 ===
<nowiki>##</nowiki> 로 시작하면 한 줄 코멘트
## 한 줄 코멘트 single-line comment
<nowiki>#* 로 시작하고 *#</nowiki>로 끝나면, 여러 줄 코멘트
#*
여러 줄 코멘트.
여기에 표시되는 내용은
Velocity Template Engine이 무시해버린다.
*#
<nowiki>#** 로 시작하고 *#</nowiki>로 끝나면, 블록 코멘트.
사실 여러 줄 코멘트와 다를 것은 별로 없다. 저자나 버전 등을 넣는데 주로 사용한다.
#**
This is a VTL comment block and
may be used to store such information
as the document author and versioning
information:
@author
@version 5
*#
=== 변수 Variable ===
변수는 $로 시작하며, [a-zA-Z0-9-_] 문자가 변수에 사용될 수 있다.
<nowiki>#set</nowiki>로 변수에 값을 세팅할 수 있다.
#set ($foo = "bar")
원래는 <nowiki>${foo}</nowiki> 형태가 정식적인(formal) 표현이다.
텍스트 중간에 변수가 들어갈 때 잘못 파싱되는 것을 방지하기 위해, 반드시 이 형태를 사용해야 할 경우가 있다.
Jack is a $vicemaniac.
Jack is a ${vice}maniac.
=== 프라퍼티 Property ===
변수 안의 프라퍼티에 접근할 수 있다.
$customer.address
$purchase.total
Java Beans 표준의 property 규칙이 그대로 사용된다. (getX(), setX() 등)
=== 메소드 Method ===
변수로부터 메소드를 곧바로 실행할 수도 있다.
$customer.getAddress()
$date.format("yyyy-MM-dd", $createTime)
=== 조용한 레퍼런스 Quiet Reference ===
만약 $foo 라고 썼는데 foo 라는 이름의 객체가 존재하지 않는다면,
$foo 라는 글자가 결과에 그대로 표현된다.
객체가 존재하지 않을 때 아무것도 표현되지 않게 하려면, $ 다음에 !를 붙인다.
<input type="text" name="email" value="$email"/>
<input type="text" name="email" value="$!email"/>
물론 정식적인 표현도 가능하다.
<input type="text" name="email" value="$!{email}"/>
=== escaping ===
'$' 를 표현하려면 \$ 로 한다. '\$' 는 '\\$' 로 표시한다.
혹은 다음과 같이 할 수 있다.
#set ($dollar = "$")
$dollar
=== 지시자 Directive ===
지시자는 #로 시작한다. ${..}와 같은 이유로, #{..} 표현도 가능하다.
#if($a==1)true enough#elseno way!#end
#if($a==1)true enough#{else}no way!#end
==== #set ====
변수에 값을 지정하기 위해 사용한다.
#set ($primate = "monkey") ## literal
#set ($monkey = $bill) ## variable reference
#set ($monkey.Friend = "monica") ## string literal
#set ($monkey.Blame = $whitehouse.Leak) ## property reference
#set ($monkey.Plan = $spindoctor.weave($web)) ## method reference
#set ($monkey.Number = 123) ## number literal
#set ($monkey.Say = ["Not", $my, "fault"]) ## ArrayList
#set ($monkey.Map = {"banana" : "good", "roast beef" : "bad"}) ## Map
#set ($value = $foo + 1)
#set ($value = $bar - 1)
#set ($value = $foo * $bar)
#set ($value = $foo / $bar)
같은 변수에 다른 값을 넣으면, 마지막 넣은 값이 저장된다.
값을 unset 하는 기능은 없다.
==== Literal ====
set 할때 문자열은 큰따옴표(") 로 감싸진다. 이 안에 변수가 있으면, 그것도 해석(parse)된다.
#set( $directoryRoot = "www" )
#set( $templateName = "index.vm" )
#set( $template = "$directoryRoot/$templateName" )
$template
결과값은
www/index.vm
하지만 작은따옴표(')로 감싸면 해석되지 않는다.
#set( $foo = "bar" )
$foo
#set( $blargh = '$foo' )
$blargh
결과는
bar
$foo
=== 조건문 if-else ===
#if ($foo < 10)
Go North
#elseif ($foo == 10)
Go East
#elseif ($bar == 6)
Go South
#else
Go West
#end
== 연산은 primitive, string, object를 비교하는데, object의 경우 toString()의 값이 비교된다.
AND 연산 : &&
#if ($foo && $bar)
This AND that
#end
OR 연산 : ||
#if ($foo || $bar)
This OR That
#end
NOT 연산 : !
#if (!$foo)
NOT that
#end
$!foo 와 !$foo 를 혼동하지 말 것!
=== 반복문 Loops ===
$allProducts가 List나 Array인 경우에는 이렇게 한다.
#foreach( $product in $allProducts )
$product
#end
$allProducts가 Map이나 Hashtable이라면, 이렇게 할 수 있다.
#foreach( $key in $allProducts.keySet() )
Key: $key -> Value: $allProducts.get($key)
#end
현재 루프 카운트는 $velocityCount로 알아올 수 있다.
#foreach( $customer in $customerList )
$velocityCount : $customer.Name
#end
$velocityCount 이름과 0부터 시작하는지 1부터 시작하는지 등은 설정 가능하다.
=== include ===
#include ("one.txt")
#include ("one.gif","two.txt","three.htm")
#include ("greetings.txt", $seasonalstock)
파일의 내용을 그대로 include한다. 여러 파일을 한꺼번에 include할 수 있다. 파일 이름에 변수가 들어갈 수 있다.
=== parse ===
#parse ("me.vm")
파일을 파싱해서 그 결과를 include한다. 한번에 하나의 파일만 가능하다.
Count down.
#set ($count = 8)
#parse ("parsefoo.vm")
All done with dofoo.vm!
#set ($count = $count - 1)
#if ($count > 0)
#parse ("parsefoo.vm")
#else
All done with parsefoo.vm!
#end
재귀적으로 사용 가능한데, 깊이가 정해져있다. 깊이는 설정 가능하고, 디폴트로 10이다.
=== stop ===
#stop
파싱을 멈춘다.
=== 매크로 ===
일종의 함수 같은 것이다.
다음과 같이 정의하고,
#macro (d)
<tr><td></td></tr>
#end
다음과 같이 사용한다.
#d()
파라미터를 매크로 이름 뒤에 변수로 받을 수 있다.
#macro (callme $a)
$a $a $a
#end
이렇게 사용한다.
#callme ($foo.bar())
== Velocity Tool ==
=== Cookie Tool ===
$cookie.foo.value
$cookie.add("cookieName", "cookieValue")
=== Import Tool ===
$import.read("http://www.rolizen.com/import/url")
=== Parameter Tool ===
$params.foo
$params.getString("foo")
$params.getNumber("foo")
$params.getInt("foo")
=== Alternator Tool ===
예를들어, 루프를 돌면서 table의 tr을 찍는데, 홀수줄은 흰색으로, 짝수줄은 회색으로 찍고 싶은 경우,
#set ($color = $alternator.auto(["fff", "eee"))
#foreach ($item in $listItems)
<tr style="background-color:#$color">...</tr>
#end
=== Date Tool ===
$date -> 2007. 2. 5 오후 3:14:43
$date.get("yyyy-MM-dd HH:mm:ss") -> 2007-02-05 15:14:43
$date.format("yyyy-MM-dd HH:mm:ss", $myDate) -> 2007-02-03 16:31:34
=== Number Tool ===
#set ($val = 1234567)
$number.format("currency", $val) -> ₩1,234,567
$number.format("integer", $val) -> 1,234,567
$number.format("0,000", $val) -> 1,234,567
$number.format("0,0000", $val) -> 123,4567
$number.format("0", $val) -> 1234567
=== Escape Tool ===
$html -> "bread" & "butter"
$esc.html($html) -> "bread" & "butter"
$xml -> "bread" & "butter"
$esc.xml($xml) -> "bread" & "butter"
$javascript -> He didn't say, "Stop!"
$esc.javascript($javascript) -> He didn\'t say, \"Stop!\"
$esc.dollar -> $
$esc.d -> $
$esc.hash -> #
$esc.h -> #
$esc.backslash -> \
$esc.b -> \
$esc.quote -> "
$esc.q -> "
$esc.singleQuote -> '
$esc.s -> '
$esc.exclamation -> !
$esc.e -> !
=== Iterator Tool ===
=== List Tool ===
List나 Array에서 엘리먼트를 get / set 할 수 있다.
$primes -> new int[] {2, 3, 5, 7}
$list.size($primes) -> 4
$list.get($primes, 2) -> 5
$list.set($primes, 2, 1) -> (primes[2] becomes 1)
$list.get($primes, 2) -> 1
$list.isEmpty($primes) -> false
$list.contains($primes, 7) -> true
=== Math Tool ===
=== Sorter Tool ===
== Velocity Tool 만드는 법 ==
=== 일반적인 Tool ===
그냥 일반적인 class를 만들면 된다. public한 field와 method를 사용할 수 있다.
=== context 를 갖는 Tool ===
public class MemberUtil {
private HttpServletRequest request;
private HttpSession session;
private MemInfoData meminfo;
public void init(Object obj) {
ChainedContext cc = (ChainedContext)obj;
this.request = cc.getRequest();
this.session = request.getSession(true);
meminfo = (MemInfoData)session.getAttribute(MemInfoData.MEMINFO_SESSION_KEY);
if (!validMemInfo(meminfo))
meminfo = null;
}
private boolean validMemInfo(MemInfoData mid) {
return (mid != null) && (mid.getMemNo() > 0) && (mid.getOpenid() != null);
}
public HttpServletRequest getRequest() {
return request;
}
public HttpSession getSession() {
return session;
}
public MemInfoData getMeminfo() {
return meminfo;
}
public boolean isLogin() {
return (meminfo != null);
}
}
위와 같이 init() 메소드를 이용해 context를 받을 수 있다.
== Velocity Editor ==
eclipse plugin : http://velocitywebedit.sourceforge.net/
http://technet.ui2.co.kr/wiki/index.php/Velocity velocity wiki 페이지
템플릿 엔진
== Spring과 함께 사용 ==
=== 전형적인 디렉토리 구조 ===
[[그림:VelocityDirectoryStructure.png]]
* velocity와 velocity tool을 사용하기 위해 필요한 jar 파일을 lib에 넣어야 한다.
** velocity-dep-*.jar : velocity 그리고 관련된 클래스 파일
** velocity-tools-*.jar : velocity tool
** commons-digester
** commons-collections
** commons-beanutils
* /WEB-INF/velocity 를 velocity template 루트로 잡는다.
* /WEB-INF/velocity/VM_global_library.vm 가 디폴트 매크로 파일이 된다.
* /WEB-INF/toolbox.xml 은 velocity tool의 설정이다.
* 각 설정파일의 위치를 변경하려면 *-servlet.xml에서 한다.
=== *-servlet.xml ===
*-servlet.xml 에 velocity 관련 설정을 넣어 사용할 수 있다.
[[SpringMVC]]를 참고할 것.
=== velocity properties ===
velocity 관련 설정은 별도의 velocity.properties를 만들어 할 수도 있지만, *-servlet.xml에서 직접 할 수도 있다. 'velocityConfig' 부분의 'velocityProperties' 부분에 property를 추가하면 된다. velocity property의 전체 항목은 velocity jar 파일의 /org/apache/velocity/runtime/default/velocity.properties 에서 확인할 수 있다.
=== VM_global_library.vm ===
예를들어 다음과 같이 만들 수 있다.
#macro (xhtml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
#end
출처
http://blog.naver.com/tellme07?Redirect=Log&logNo=120061531772
'[IT] > 컴퓨터' 카테고리의 다른 글
[컴퓨터][백신]백신프로그램 업데이트 막는 악성코드 치료하기 (0) | 2012.05.02 |
---|---|
[자바]Struts2, Spring, iBatis 사용 (0) | 2012.05.02 |
[개발자][DB][소식] SQL server 관리 실무, 정부 무료교육 (0) | 2012.04.23 |
[유틸]컴퓨터 포맷후 드라이버 자동검색툴 - 3DP Chip v11.10 (0) | 2012.04.22 |
[유틸]색상 정보 추출 프로그램 - Eclipse Palette (무료) (0) | 2012.04.22 |
- Total
- Today
- Yesterday
- 치노
- 믹스 블로그
- 스포토리
- 분당 JJ
- [NeW] 한밤의 연예가 섹션 2.0
- 낭만얼리엄의 dream factory
- 흐르는 강물처럼..
- 서른 살의 철학자, 여자
- 런던포인터닷컴(에핑그린)
- 탐진강의 함께 사는 세상 이야기
- 김문기의 PhotoLand 입니다~^^
- 고양이 책방
- 아이돌박스
- 웅크린 감자의 리뷰
- 맛순이
- 푸드앤카페
- 포투의 기사
- 공간IT
- 희망을 보고, 나는 쓰네
- 딘델라의 세상보기
- 내가 숨 쉬는 공간의 아름다움
- 고요한 산사의 풍경소리
- KooJinWook
- 설리아닷컴
- 서른 살의 철학자, 여자
- Happy Virus!!! :: 추억의 시티폰 VS 추…
- Happy Virus!
- INFORMATION FACTORY
- Home: WorkingUS.com
- 피오나의 아름다운 이야기 모음.
- 시사인
- Bloter.net
- 유저스토리북
- 트윗믹스
- 트렌드믹스
- 펫러브즈미
- 네이버오픈캐스트
- 위자드팩토리
- 블로그 쉐어
- 애드젯
- 아파트투유
- Travel&Life LOTTEJTB
- 오라클클럽
- 오픈후르츠
- SLRCLUB, 디지털 사진가를 위한 커뮤니티
- 처절한 몸부림(헬스트레이너)
- 테너 이강호 홈페이지
- 라벨라오페라 학교
- Go! classic 고전음악 애호가들을 위한 공간
- Ceramic Palace Hall
- 음악춘추사 공식 홈페이지
- 클래식코리아™ 대한민국 클래식 1위
- Soprano Eunbok Lee
- 한국야구위원회
- 아프리카 스포츠TV
- KBSN 아나운서 블로그
- Twitter / yeonjae0528
- 금융감독원
- 한국소프트웨어산업협회
- 산림청 대표 블로그 "푸르미의 산림이야기"
- 하루하나
- 무늬만 개발자 -All of Software-
- 커니의 안드로이드 이야기 - Android Human
- Being Myself
- 신규하 블로그
- 신세계뮤직21(포토샵)
- 녹두장군 - 안드로이드, 아이폰, C#, VC++, …
- 조대협의 블로그
- 클리앙
- 문화
- 소식
- 핫이슈
- 야구
- 화제
- 300초
- 강습
- 뜨는 사진
- 시구
- 경제
- 개콘
- 포토
- 정치
- 총선
- 핫뉴스
- 슬라이딩
- 개그콘서트
- 사회
- IT
- 사진
- 탑밴드2
- Top밴드2
- 영상
- 풀버전
- 화제의 시구
- 선거
- TOP밴드
- 수영
- 다시보기
- 탑밴드
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |