not set

velocity 문법 본문

grammar/velocity

velocity 문법

다크곰 2009. 5. 29. 16:17

* 변수(Variables)와 #set 지시자(Directive)

Velocity Templating Language(VTL)는 변수들에 대한 단순한 규칙을 가지고 있다. Velocity는 템플릿내의 변수참조를 객체를 대표하는 문자(String)으로 변환한다.

만약 객체가 String이 아닐 경우, Velocity는 출력을 만들 변수로서 toString() 메소드를 호출하게 된다.

이는 기본적인 행위이며, 우리가 원하는 출력을 갖기 위해서 toString() 메소드를 오버라이드(override) 할 수도 있다.
=====================================
변수 명칭은 다른 프로그래밍 언어들과 유사하며, 명칭은 반드시 문자(대문자 또는 소문자)로 시작해야 한다.

그러나 뒤따라 오는 문자들은 문자, 숫자, underscores(_), hyphens(-)으로 구성될 수도 있다.
=====================================
변수에 값을 할당하기 위해서는 Velocity의 지시자를 사용할 필요가 있다. 모든 지시자의 접두어는 #(hash symbol)이다.

몇몇 지시자들은 Velocity 내부에 정의되어져 있고 Velocity Macros라 불리는 매크로(macros)를 이용해서 정의된 것도 있다.

#set 지시자는 Java 변수에 할당하는 것처럼 동일하게 특정 값을 할당한다.
=====================================
Velocity Template 예

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

#set ($dog = "Jindo")


The dog is named $dog.

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

Velocity Template의 결과는 The dog is named Jindo. 가 된다.
=====================================
* Quiet Reference Notation

Velocity는 Context 내에 변수가 존재하지 않으면 참조 변수명을 그대로 Display한다. 이는 원 Text 내에 참조를 포함하고 있기 때문이다. 간단한 예를 보자.

Velocity template: $pizza will not do anything special

Result: $pizza will not do anything special


만약 우리가 은밀한 참조 표기(Quiet Reference Notation)를 사용하게 되면 템플릿 엔진은 존재하지 않는 참조를 Display하지 않을 것이다. 이때는 exclamation point(!)를 dollor표시 뒤에 추가하면 된다.

Velocity template: $!pizza will hide itself

Result: will hide itself
=====================================
* 문자 연결

Velocity 내의 새로운 문자에 2개 또는 그 이상의 문자들을 쉽게 할당할 수 있다. 특정 변수에 할당하기 위해서는 = 을 이용한다.

Velocity template

#set ($city = "Austin")

#set ($state = "Texas")
=====================================
#set ($address = "$city, $state")

This is the address : $address
=====================================
Result - This is the address : Austin, Texas
=====================================
또한 좀 더 세밀한 문자 표기가 가능하다. 레프런스 변수명을 {}로 둘러싸면 된다.

예를 들어

#set ($city = "Austin")

#set ($state = "Texas")


#set ($myAddress = "${city}isin$state")

This is the weird address: $myAddress


Result - This is the weird address: AustinisinTexas

만약 {}가 없다면 결과는 다음과 같다. This is the weird address: $cityisinTexas

Velocity에서 "+" 연산자는 산술 연산자로만 쓰이며 문자 연결시에는 사용할 수 없다.

문자열 연결을 하고자 할 경우에는 #set ($string3 = "$string1$string2") 형태로 사용해야 한다.


* 주석 (Comments)

Velocity에서의 주석은 ##(double hash)가 라인 주석, #*.....*#가 multi-line 주석으로 사용한다.

사용 예는 아래와 같다.

Velocity template:

## line comment

Some text in the template

#* A two-line

block comment *#


Result:

Some text in the template


* Escapting Rules

템플릿 내부의 특수문자 사용을 하기 위해서는 backslash를 이용해서 표현한다.

사용 예.

Velocity template:

#set ($string = "something")

$string

\$string


Result:

something

$string


만약 $string이 변수 참조로 선언되어져 있지 않다면

$string

\$string


Velocity template:

#set ($hash = "#")

$hash$hash


Results:

##
=====================================
* Collections

Velocity는 다른 몇몇 Collection 타입을 다룰수 있다.(Collection, Map, Iterator, Enumeration, Arrays of objects)


Velocity는 내부적으로 #foreach...#end 지시자를 이용해서 Iterator 인스턴스를 사용한다.

collections와 maps, 객체로 부터 직접 Iterator를 가져오기 위해서 Iterator 인스턴스를 사용.

arrays와 enumerations를 위해서 Velocity 내부에 Iterator Interface를 구현한 객체내부에 array 또는 enumeration을 wrapping하고 있다.

#foreach 문 내에 Iterator 또는 Enumeration이 사용되었을 경우 log 파일에 warning 메시지가 표시될 수 있다. 가능한 Collection을 이용할 경우 Collection, Map 또는 array를 가능한 사용하도록 하자.


* Control Flow Directives

Velocity에서는 2가지의 흐름 지시자가 있다. (#if...#else...#elseif....#end 와 #foreach...#end)

이것은 Velocity를 아주 단순한 프로그래밍 언어로 만든다.


#if...#else...#elseif...#end

#if 지시자(directive)는 다른 언어의 if 문과 유사하다. #if 는 #elseif 또는 #else가 뒤따라오게 된다.

#end는 #if문을 종료한다. Velocity에서 지원되는 logical(or Boolean) operator는 AND(&&), OR(||), NOT(!)이 있다.


Velocity에서 #if 또는 #elseif 조건에서 평가는 3가지 규칙을 따른다.

1.Boolean 객체를 위한 값은 반드시 true여야 한다.

2.Context내에 참조변수가 없을 경우 Velocity는 false로 평가한다.변수에 의한 객체 참조가 null이 아닐 경우 조건은 true가 된다. 따라서 Context내의 변수들은 결코 null 이어서는 안됨을 기억해라.

3.문자열의 true, false는 현재 시점에 평가된다. 이것은 Velocity Macros라 불리는 매크로 내부에 arguments로 사용할 경우 유용하다.


사용 예. Velocity template:

#set ($pages = 5)

#if ($pages == 0)

    There are no pages to display.

#elseif ($pages = 1)

    This the only page.

#else

    There are $pages pages that can be shown.

#endif

Result: There are 5 pages that can be shown.
=====================================

사용 예. Velocity template:

#if ($novalue)
  No value - we won't see this
#else
  The novalue variable doesn't exist
#end

#set ($something = "something")
#if ($something)
  $something
#end

#if (true)
  This statement is true.
#else
  This statement is false.
#end

Result:

The novalue variable doesn't exist

something

This statement is true.
=====================================
Context내에 $notavariable변수가 없을 경우

사용 예. Velocity template:

#if (!true)
  This statement is true.
#else
  This statement is false.
#end

#if (true && $notavariable)
  This statement is true.
#else
  This statement is false.
#end

#if (true || $notavariable)
  This statement is true.
#else
  This statement is false.
#end
Result:

This statement is false.
This statement is false.
This statement is true.


'grammar > velocity' 카테고리의 다른 글

velocity란 무엇인가.  (0) 2009.05.29