[java html template engine] [Velocity] velocity 기본 문법
2022.08.10 21:53
[java html template engine] [Velocity] velocity 기본 문법
1. Velocity란?
Velocity는 자바 기반의 템플릿 엔진이다.
Velocity는 웹 페이지 디자이너들이 자바 코드안에서 정의된 메소들에 접근하는 것을 도와준다. 이것은 웹 페이지 디자이너들이 자바 개발자들과 함께 Model-View-Controller(MVC) 아키텍쳐에 따른 웹 사이트를 각자의 영역에서 최선의 결과를 가져오도록 도와준다는 것을 의미한다.
Velocity는 웹 페이지로부터 자바 코드를 분리할 수 있고, 웹사이트를 계속 오랫동안 유지할 수 있으며, 자바 서버 페이지(JSP)의 실용적인 대안을 제공한다.
2. VTL (Velocity Template Language)
3. 사용법
- Hello, World!
|
#set ($foo = "velocity") |
|
Hello #foo World! |
|
## Hello velocity World! 출력 |
- 문자열
명령어 #set을 사용할 때 큰 따옴표로 지정된 문자열은 아래 예제처럼 파싱되어 출력된다.
|
#set( $directoryRoot = "www" ) |
|
#set( $templateName = "index.vm" ) |
|
#set( $template = "$directoryRoot/$templateName" ) |
|
$template |
|
## www/index.vm 출력 |
그러나 문자열이 작은 따옴표일 때는 파싱되지 않는다.
|
#set( $foo = "bar" ) |
|
$foo |
|
## bar 출력 |
|
#set( $blargh = '$foo' ) |
|
$blargh |
|
## $blargh 출력 |
- 조건문
Velocity에서 #if 명령어는 문장이 참인 조건에서 웹페이지가 생성될 때 포함될 문자열을 지정할 수 있다.
|
#if( $foo > 10 ) |
|
Go North |
|
#elseif( $foo == 10 ) |
|
Go East |
|
#elseif( $bar == 6 ) |
|
Go South |
|
#else |
|
Go West |
|
#end |
- 논리 연산자
자바, C랑 동일하다.
|
## logical AND |
|
|
|
#if( $foo && $bar ) |
|
This AND that |
|
#end |
|
|
|
|
|
## logical OR |
|
|
|
#if( $foo || $bar ) |
|
This OR that |
|
#end |
|
|
|
|
|
##logical NOT |
|
|
|
#if( !$foo ) |
|
NOT that |
|
#end |
- 반복문
for문이 없다, foreach문만 존재한다.
|
<ul> |
|
#foreach( $product in $allProducts ) |
|
<li>$product</li> |
|
#end |
|
</ul> |
카운트 기능도 기본적으로 존재한다. 내부 객체이다.
|
<table> |
|
#foreach( $customer in $customerList ) |
|
<tr><td>$velocityCount</td><td>$customer.Name</td></tr> |
|
#end |
|
</table> |
기본값은 $velocityCount이며, velocity.properties에서 확인 및 변경이 가능하다.
|
velocity.properties |
|
|
|
# Default name of the loop counter |
|
# variable reference. |
|
directive.foreach.counter.name = velocityCount |
|
|
|
# Default starting value of the loop |
|
# counter variable reference. |
|
directive.foreach.counter.initial.value = 1 |
- 산술 연산
수학적 기능은 정수만 가능하다.
|
#set( $foo = $bar + 3 ) |
|
#set( $foo = $bar - 4 ) |
|
#set( $foo = $bar * 6 ) |
|
#set( $foo = $bar / 2 ) |
|
|
|
#set( $foo = $bar % 5 ) |
- 범위 연산
범위연산은 #set 과 #foreach 구문에서 사용 가능하다 다음과 같은 구조를 가진다.
[n..m]
다음은 사용 예제이다.
|
First example: |
|
#foreach( $foo in [1..5] ) |
|
$foo |
|
#end |
|
|
|
Second example: |
|
#foreach( $bar in [2..-2] ) |
|
$bar |
|
#end |
|
|
|
Third example: |
|
#set( $arr = [0..1] ) |
|
#foreach( $i in $arr ) |
|
$i |
|
#end |
|
|
|
Fourth example: |
|
[1..3] |
결과는 다음과 같다.
|
First example: |
|
1 2 3 4 5 |
|
|
|
Second example: |
|
2 1 0 -1 -2 |
|
|
|
Third example: |
|
0 1 |
|
|
|
Fourth example: |
|
[1..3] |
결과
Velocity 기본문법에 대해 알아보았다.
[출처] https://kkkapuq.tistory.com/81
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.