4,562,712 th visitor since 2017.2.1 ( Today : 163 )
Programming
No. 546
Name. swindler
Subject. Velocity Guide (한글)
Main Cate. etc
Sub Cate.
Date. 2009-01-22 13:41
Hit. 18915 (211.43.206.101)
File.


목 차



  1. 이 가이드에 관하여
  2. 베로시티 란 ?
  3. 베로시티로 무엇을 할 수 있나 ?

    1. 진흙 가게 예

  4. 베로시티 템플릿 언어 (VTL) : 도입
  5. 안녕 베로시티
  6. 주석 처리
  7. References

    1. Variables
    2. properties
    3. Methods

  8. Formal Reference Notation
  9. Quiet Reference Notation
  10. Getting LIteral

    1. Currency
    2. Escaping VaLId VTL References

  11. Case Substitution
  12. Directives

    1. Set
    2. String LIterals
    3. If-Else Statements

      1. Relational and Logical Operators

    4. Foreach Loops
    5. Include
    6. parse
    7. Stop
    8. Velocimacros

  13. Escaping VTL Directives
  14. VTL : Formatting Issues
  15. Other Features and Miscellany

    1. Math
    2. Range Operator
    3. Advanced Issues: Escaping and !
    4. Velocimacro Miscellany
    5. String Concatenation

  16. Feedback


1. 이 가이드에 관하여


The Velocity User Guied is intended to help page designers and content providers get acquainted with velocity and the syntax of its simple yet powerful scripting language, the velocity Template Language(VTL). Many of the examples in this guide deal with using velocity to embed dynamic content in web sites, but all VTL examples are equally appLIcable to other pages and templates.


베로시티 사용자 가이드는 디자이너들을 도와주고, 내용제공자들 에게는 베로시티와 아직 강력한 scripting 언어인 베로시티 템플릿 언어(VTL)의 문장론에 정통하게 된다. 가이드의 많은 예들은 웹 사이트에 베로시티를 사용하여 다이나믹한 내용을 끼워넣는 다룬다. 그러나 모든 VTL 예들은 다른 페이지와 템플릿에 똑같이 적용가능하다.



2. 베로시티 란


Velocity is a jave-based template engine. It permits web page designers to reference methods defined in Java code. Web designers can work in parallel with Java programmers to develop web sites according to the Model-View-ContrOLler (MVC) model, meaning that web page designers can focus sOLely on creating a well-designed site, and programmers can focus sOLely on writing top-notch code. velocity separates Java code from the web pages, making the web site more maintainable over the long run and providing a viable alternative to Java Server pages (JSps) or pHp.


베로시티는 자바기반의 템플릿 엔진 입니다. 그것은 웹 페이지 디자이너들이 자바 코드안에서 정의된 방법들을 레퍼런스하는 것을 허락합니다. 웹 디자이너들은 자바 프로그래머들과 함께 Model-View-Controller(MVC) 모델에 의해 웹 사이트를 웹 페이지 디자이너들이 잘 디자인된 웹사이트에 초점을 맞춰 개발 할 수 있다는 것을 의미합니다. 그리고 프로그래머들은 혼자서 top-notch 코드를 쓰는 것에 초점을 맞출 수 있습니다. 베로시티는 웹 페이지로부터 자바 코드를 분리할수 있고. 웹사이트를 계속 오랫동안 유지할수 있으며, 자바 서버 페이지의 실용적인 대안을 제공합니다.


elocity can be used to generate web pages, SQL, postScript and other output from templates. It can be used either as a standalone utiLIty for generating source code and reports, or as an integrated component of other systems. When complete, velocity will provide template services for the Turbine web appLIcation framework. velocity+Turbine will provide a template service that will allow web appLIcations to be developed according to a true MVC model.


베로시티는 웹 페이지, SQL, PostScript 그리고 템플릿들로부터의 다른 결과를 내는데 사용될 수 있습니다. 그것은 generating 소스 코드와 레포트를 위한 독립적인 utility이고 다른 시스템에 통합된 콤퍼넌트로서 사용될수 있습니다. 그것을 끝냈을때, 베로시티가 터빈 웹 적용 프레임워크를 위해 템플릿 서비스들을 준비할 것입니다. 베로시티 + 터빈은 웹 application들이 true MVC 모델에 따라 개발될 수 있도록 서비스를 제공합니다.



3. 베로시티로 무엇을 할 수 있나



  • The Mud Store Example

Suppose you are a page designer for an online store that specializes in selling mud. Let's call it "The Online Mud Store". Business is thriving. Customers place orders for various types and quantities of mud. They login to your site using their username and password, which allows them to view their orders and buy more mud. Right now, Terracotta Mud is on sale, which is very popular. A minority of your customers regularly buys Bright Red Mud, which is also on sale, though not as popular and usually relegated to the margin of your web page. Information about each customer is tracked in your database, so one day the question arises, Why not use velocity to target special deals on mud to the customers who are most interested in those types of mud?


당신이 진흙을 파는 것을 온라인가게의 페이지 디자이너 이라고 가정하시오. 그것을 "온라인 진흙 가게" 라고 부릅시다. 사업이 번성하고 있습니다. 고객들 다양한 종류와 다양한 수량을 주문합니다. 고객들은 사용자 이름과 패스워드를 입력하고 당신의 사이트에 로그인하여 고객자신이했던 주문을보고, 또 다른 진흙을 삽니다. 바로 지금, 테라코타 진흙이 판매중이고, 매우 인기가 좋습니다. 당신의 고객들의 소수가 판매중이지만 테라코타 진흙만큼 인기 있지 않고 당신의 웹페이지 이익에 비중이 작은 Bright Red 진흙을 정기적으로 구입합니다. 각 고객에 관한 정보는 당신의 데이타 베이스안에 저장되고, 그러던 어느날 왜 앞에서 언급한 타입의 진흙에 대해 가장 흥미를 가지고 있는 고객들과의 특별한 거래를 찾는데 베로시티를 사용하지 않는지에 대한 의문이 떠오른다.


velocity makes it easy to customize web pages to your online visitors. As a web site designer at The Mud Room, you want to make the web page that the customer will see after logging into your site.


베로시티는 웹페이지를 당신의 온라인 방문객들에게 판매를 쉽게 해줍니다. 진흙 가게의 웹사이트 디자이너인 당신은 고객이 당신의 웹 사이트에 로그인 한 후에 보게 될 웹 페이지를 만들기 원합니다.


You meet with software engineers at your company, and everyone has agreed that $customer will hold information pertaining to the customer currently logged in, that $mudsOnSpecial will be all the types mud on sale at present. The $flogger object contains methods that help with promotion. For the task at hand, let's concern ourselves only with these three references. Remember, you don't need to worry about how the software engineers extract the necessary information from the database, you just need to know that it works. This lets you get on with your job, and lets the software engineers get on with theirs.


당신이 소프트웨어 엔지니어들과 회사에서 만나고, $customer가 현재 판매 중인 모든 타입의 진흙을 판매게 될 $mudsOnSpecial에 현재 로그인하고 있는 고객에 대한 정보를 갖게 되는 것에 모두 동의합니다. $flogger는 판매상품과 함께 도울 메소드를 포함합니다. 웹페이지를 만들 때, 우리 스스로 오직 세가지 레퍼런스에 대해 생각해봅시다. 명시하십시오, 당신은 소프트웨어 엔지니어들이 데이터베이스에서 필요한 정보를 어떻게 추출하는지에 대해 걱정할 필요없습니다. 당신은 단지 그것이 작동한다는 것을 알면 됩니다. 그렇게되면 당신은 당신의 일을 하게 되고, 소프트웨어 엔지니어들은 그들의 일을 하게 됩니다.


You could embed the following VTL statement in the web page:


당신은 웹 페이지안에 다음의 VTL statement를 끼워넣을 수 있었습니다:


Hello $customer.Name!
$flogger.getpromo( $mud )


he exact details of the foreach statement will be described in greater depth shortly; what's important is the impact this short script can have on your web site. When a customer with a penchant for Bright Red Mud logs in, and Bright Red Mud is on sale, that is what this customer will see, prominently displayed. If another customer with a long history of Terracotta Mud purchases logs in, the notice of a Terracotta Mud sale will be front and center. The flexibility of velocity is enormous and imited only by your creativity.


foreach 명령문의 정확한 세부내용은 좀더 깊고 간단하게 설명될 것입니다; 중요한 것은 이 짧은 script가 당신의 웹 사이트에서 일이킬 수 있는 충돌입니다. Bright Red 진흙을 사려는 고객이 로그인했을 때 'Bright Red Mud is on sale' 이 두드러지게 배치되어 그 고객이 보게 될 것입니다. 만약 테라코타 진흙을 오랫동안 구입해온 기록을 가진 고객이 로그인한다면 Terracotta Mud sale에 대한 통지는 가운데 정면에서 보여질 것입니다. 베로시티의 유연함은 막대하고 다만 당신의 창의력에 의해 제한될 것입니다.


Documented in the VTL Reference are the many other velocity elements, which collectively give you the power and flexibility you need to make your web site a web presence As you get more familiar with these elements, you will begin to unleash the power of velocity.


VTL 레퍼런스안에 기록된 것은 다른 많은 베로시티의 요소들입니다. 이 요소들이 당신이 웹사이트를 만들 때 필요한 power와 flexibility를 총괄적으로 제공합니다. 당신이 이 요소들에 대해 좀 더 친숙해지는만큼, 당신은 메로시티의 힘을 해방시키기 시작할 것입니다.



4. 베로시티 템플릿 언어 (VTL) : 도입


The velocity template Language (VTL) is meant to provide the easiest, simplest, and cleanest way to incorporate dynamic content in a web page. Even a web page developer with little or no programming experience should soon be capable of using VTL to incorporate dynamic content in a web site.


베로시티 템플릿 언어(VTL)은 웹 페이지에서 동적인 내용을 구체화하기 가장 쉽고, 가장 간결하고 가장 확실한 방법을 제공하는 수단입니다. 심지어 프로그래밍해본 경험이 적거나 없는 페이지 개발자도 웹사이트에서 동적인 내용를 구체화하는데 VTL을 금방 사용할 수 있을 것입니다.


VTL uses references to embed dynamic content in a web site, and a variable is one type of reference. Variables are one type of reference that can refer to something defined in the Java code, or it can get its value from a VTL statement in the web page itself. Here is an example of a VTL statement that could be embedded in an HTML document:


VTL은 웹사이트에서 동적인 내용을 끼워넣는데 레퍼런스를 사용합니다. 그리고 레퍼런스의 타입은 variable입니다 . Variables는 자바 코드에서 정의된 것에 대해 언급할 수 있는 레퍼런스의 한 타입 이거나, 그것은 웹페이지 자체의 VTL 문장으로부터 스스로의 값을 얻을 수 있습니다. HTML 문서안에 삽입될 수 있는 VTL문의 예가 여기 있습니다:



#set ( $a = "velocity" )


This VTL statement, like all VTL statements, begins with the # character and contains a directive : set. When an online visitor requests your web page, the velocity Templating Engine will search through your web page to find all # characters, then determine which mark the beginning of VTL statements, and which of the # characters that have nothing to do with VTL.


이 VTL문은 모든 VTL문처럼 #기호로 시작하고 set 명령어를 포함합니다. 온라인의 손님이 당신의 웹 페이지를 요청할 때, 베로시티 Templating 엔진은 당신의 웹 페이지를 모든 #기호를 찾기 위하여 검색할 것입니다. 그러고나서 VTL문를 시작할 #기호와 VTL에서 아무일도 않하는 #기호들을 결정합니다.


The # character is followed by a directive, set. The set directive uses an expression enclosed in brackets) -- an equation that assigns a value to a variable. The variable is listed on the left hand side and its value on the right hand side; the two are separated by an = character.


#set 명령어 다음에 #기호가 옵니다. set 명령어는 둥근괄호(')')안에서 사용합니다. 등식은 변수에 값를 부여합니다. 변수는 좌변에, 변수의 값는 우변에 나열됩니다; 좌변과 우변은 = 기호로 구분되어 집니다.


In the example above, the variable is $a and the value is velocity. This variable, like all references, begins with the $ character. value are always enclosed in quotes; with velocity there is no confusion about data types, as only strings (text-based information) may be passed to variables.


위의 예에서, 변수는 '$a'이고 값은 'Velocity'입니다. 이 변수는 모든 레퍼런스들처럼 $기호로 시작합니다. 값은 항상 인용부호로 안에 존재합니다; 베로시티를 사용할 때 데이타 타입들에 관한 혼란은 없습니다. 단지 문자열(문자를 기반으로한 정보)변수 것들에게 건네질 수 있습니다.


The following rule of thumb may be useful to better understand how velocity works:References begin with $ and are used to get something. Directives begin with # and are used to do something.


다음의 following rule of thumb은 베로시티가 어떻게 작동하는지 좀더 잘 이해하는데 유용합니다.: 레퍼런스는 $로 시작하고 어떤 것을 얻는데 사용됩니다. 명령어는 #로 시작하고 어떤 것을 하는데 사용됩니다.


In the example above, #set is used to assign a value to a variable. The variable,$a, can then be used in the template to output "velocity".


위의 예제에서, #set는 변수에게 값을 할당하는데 사용됩니다. 변수 $a는 템플릿에서 "베로시티"를 출력하는데 사용될 수 있습니다.



5. 안녕 베로시티


Once a value has been assigned to a variable, you can reference the variable anywhere in your HTML document. In the following example, a value is assigned to $foo and later referenced.


한번 변수에 값을 할당했으면, 당신은 당신의 HTML 문서안 어디서나 변수를 레퍼런스할 수 있습니다. 다음의 예에서 $foo에 값이 할당되고 그후 레퍼런스 됩니다.



  #set ($ foo = "velocity" )
Hello #foo World!


he result is a web page that prints "Hello velocity World!".


이 결과는 "Hello Velocity World!"를 웹페이지에 출력합니다.


To make statements containing VTL directives more readable, we encourage you to start each VTL statement on a new line, although you are not required to do so. The set directive will be revisited in greater detail later on.


VTL 명령어들을 포함한 문장를 좀더 읽기 쉽게 만들기 위해, 여러분이 굳이 그럴 필요는 없지만 VTL문장을 새로운 줄에서 시작하도록 권장합니다. set 명령어는 나중에 매우 세부적으로 다시 찾아야될 것입니다.



6. 주석 처리


Comments allows descriptive text to be included that is not placed into the output of the template engine. Comments are a useful way of reminding yourself and explaining to others what your VTL statements are doing, or any other purpose you find useful. Below is an example of a comment in VTL.


주석은 설명적인 텍스트가 템플릿 엔진의 결과에 속하지 않는 것에 포함되게 합니다. 주석은 당신 자신을 상기시키거나 당신의 VTL문이 무엇을 하고 있는지 또는 당신이 찾는 다른 다른 목적들을 설명하기에 유용한 방법이다. 아래에 VTL의 주석의 예가 있습니다.



##This is a single line Comment.


A single line comment begins with ## and finishes at the end of the line. If you're going to write a few lines of commentary, there's no need to have numerous single line comments. Multi-line comments, which begin with #* and end with *#, are available to handle this scenario.


한줄 주석문은 ##로 시작하고 라인의 끝에서 끝납니다. 당신이 몇줄의 주석을 쓴다면, 다수의 한줄 주석으로 쓸필요는 없습니다. #*로 시작하고 *#로 끝나는 Multi-line comments가 이런 상황에 매우 유용하다.



This is text that is outside the multi-line comment.
Online visitors can see it.
#*
Thus begins a multi-line comment. Online visitors won't
see this text because the velocity Templating Engine will
ignore it.
*#
Here is text outside the multi-line comment; it is visible.


Here are a few examples to clarify how single line and multi-line comments work:


여기 한줄과 여러줄의 주석이 어떻게 작동하는지 명확하게 보여주는 몇 개의 예들이 있다.



## This text is not.
This text is visible.
This text is visible. #* This text, as part of a multi-line comment,
is not visible. This text is not visible; it is also part of the
multi-line comment. This text still not visible. *# This text is outside
the comment, so it is visible.
## This text is not visible.


There is a third type of comment, the VTL comment block, which may be used to store such information as the document author and versioning information:


VTL 주석 블럭이라는 세 번째 타입의 주석이 있습니다. 이것은 문서의 저자와 버전정보와 같은 정보를 저장하는데 사용될 수 있습니다:



#**
This is a VTL comment block and
may be used to store such information
as the document author and versioning
information:
@author
@version 5
*#



7. References


There are three types of references in the VTL: variables, properties and methods. As a designer using the VTL, you and your engineers must come to an agreement on the specific names of references so you can use them correctly in your templates.


VTL안에서 세가지 타입의 레퍼런스가 있습니다: 변수, 속성,메소드. 디자이너가 VTL을 이용할때, 당신과 당신의 엔지니어들은 당신의 템플릿에서 레퍼런스를 정확히 사용하기위해 레퍼런스의 특별한 이름을 지어주어야 합니다.


Everything coming to and from a reference is treated as a String object. If there is an object that represents $foo(such as an Integer object), then velocity will call its .toString() method to resolve the object into a String.


레퍼런스로 오고 가는 모든 것은 문자열 객체로 처리됩니다. 만약 $foo(정수 객체와 같은)를 표현하는 객체가 있다면 베로시티는 문자열에서 객체를 해결하기위한 매소드로 .toString()를 요청 할 것입니다.


Variables

he shorthand notation of a variable consists of a leading "$" character followed by a VTL Identifier. A VTL Identifier must start with an alphabetic character (a .. z or A .. Z). The rest of thecharacters are limited to the following types of characters:


변수의 속기 표기법은 VTL 식별자로부터 불려온 leading“$”기호로 구성됩니다. VTL식별자는 알파벳 (a...z, or A...Z)로 시작해야합니다. 나머지 아래있는 타입들의 문자들로 제한됩니다.




  • alphabetic (a .. z, A .. Z)
  • numeric (0 .. 9)
  • hyphen ("-")
  • underscore ("_")


Here are some examples of valid variable references in the VTL:


여기 VTL안에서 유효한 변수 레퍼런스의 예가 몇 개 있습니다:



$foo
$mudSlinger
$mud-slinger
$mud_slinger
$mudSlinger1


When VTL references a variable, such as $foo, the variable can get its value from either a set directive in the template, or from the Java code. For example, if the Java variable $foo has the value bar at the time the template is requested, bar replaces all instances of $foo on the web page. Alternatively, if I include the statement


VTL 변수가 $foo 와 같이 레퍼런스 될때, 변수는 템플릿안의 set 명령어나 자바 코드로부터 값을 얻을 수 있습니다. 예를 들어 만약 자바 변수 $foo가 template이 요청된 시간에 value bar를 가지고 있다면,bar는 웹페이상의 $foo의 모든 경우에 대체 할 것입니다. 상대적으로, 만약 내가 statement를 포함한다면



#set ( $Foo = "bar" )


The output will be the same for all instances of $foothat follow this directive.


결과는 이 명령어를 따르는 #foo의 모든 경우에 같아질 것입니다.




  • properties


The second flavor of VTL references are properties, and properties have a distinctive format. The shorthand notation consists of a leading $ character followed a VTL Identifier, followed by a dot character (".") and another VTL Identifier. These are examples of valid property references in the VTL:


VTL 레퍼런스들의 두번째 특징은 속성이고, 속성은 특유의 포맷을 가집니다. 속기 표기법은 점 기호(".")와 다른 VTL 식별자가 뒤에 따르는 leading $기호로 구성됩니다. 이들이 VTL안의 valid property references의 예입니다.



$customer.Address
$purchase.Total


Take the first example, $customer.Address. It can have two meanings. It can mean, Look in the hashtable identified as customer and return the value associated with the key Address. But $customer. Address can also be referring to a method (references that refer to methods will be discussed in the next section); $customer.Address could e an abbreviated way of writing $customer.getAddress(). When your page is requested, velocity will determine which of these two possibilities makes sense, and then return the appropriate value.


첫번째 예는 $customer.Address입니다. $customer.Address는 두가지 의미들을 가지고 있을 수 있습니다. 그것은 identified hashtable 안에서 보는 것고 키주소와 관련된 가치를 돌려주는것을 의미합니다. 그러나 $customer.Address은 또한 매소드로 언급할 수 있습니다. (매소드를 언급하는 레퍼런스는 다음 부분에서 의논할 것입니다); $customer.getAddress()는 $ customer.Address로 생략해서 사용할수 있습니다. 당신의 페이지가 요청될 때, 베로시티는 이들 두 가능성을 이치에 맞는지 분별하여 적당한 값은 return합니다.




  • Method


A method is defined in the Java code and is capable of doing something useful, like running a calculation or arriving at a decision. Methods are references that consist of a leading "$" character followed a VTL Identifier, followed by a VTL Method Body. A VTL Method Body consists of a VTL Identifier followed by an left parenthesis character ("("), followed by an optional parameter list, followed by right parenthesis character (")"). These are examples of valid method references in the VTL:


메소드는 자바코드안에서 정의되고 계산을 하거나 결정에 도출하는 것과 같이, 유용한 무언가를 할수있습니다. 매소드는 VTL 식별자 leading가 뒤에 따르고 그 뒤에 VTL Method Body 가 따라오는 "$" 기호로 구성하는 레퍼런스입니다. VTL Method Body는 left parenthesis character ("("), optional parameter list, right parenthesis character (")")의 순서로 뒤따르는 VTL 식별자로 구성됩니다. 이들이 VTL안의 valid 매소드 레퍼런스들의 예입니다 :



$customer.getAddress()
$purchase.getTotal()
$page.setTitle( "My Home page" )
$person.setAttributes( ["Strange", "Weird", "Excited"] )


The first two examples -- $customer.getAddress() and $purchase.getTotal() -- may look similar to those used in the properties section above, $customer.Address and $purchase.Total. If you guessed that these examples must be related some in some fashion, you are correct!


첫번째 두 예 -- $customer.getAddress() 와 $purchase.getTotal() -- 위의 속성부분 에서사용된 $customer.Address와 $purchase.Total과 유사해 보일 수 있습니다. 당신이 이 예들이 어떤 방식에서 무언가 관계가 있을 것이라고 추측했다면, 그 추측은 정확합니다!


VTL properties can be used as a shorthand notation for VTL Methods. The property $customer.Address has the exact same effect as using the Method $customer.getAddress(). It is generally preferable to use a property when available. The main difference between properties and Methods is that you can specify a parameter list to a Method.


VTL 속성은 VTL 메소드의 속기 표기법으로 사용될 수 있습니다. property $customer.Address는 매소드 $customer.getAddress()를 사용하는 것과 똑같은 효과가 있습니다. 이용할 수 있는 Property를 사용하는 것은 일반적으로 더 낫습니다. Property 와 Method 사이의 주요한 차이는 당신이 메소드에 parameter list를 명확히 지정할 수 있는가입니다.


The shorthand notation can be used for the following Methods.


속기 표기법은 다음의 메소드를 위하여 사용될 수 있습니다.



$sun.getplanets()
$annelid.getDirt()
$album.getphoto()


We might expect these methods to return the names of planets belonging to the sun, feed our earthworm, or get a photograph from an album. Only the long notation works for the following Methods.


우리가 이들 방법들을 태양계에 속한 행성들의 이름들을 돌려주고, 지렁이에게 먹이를 주고, 또한 앨범으로부터 사진을 얻는 것을 기대할 수 있습니다. 단지 긴 표기법이 다음의 메소드를 위하여 적용됩니다.



$sun.getplanet( ["Earth", "Mars", "Neptune"] )
## Can't pass a parameter list with $sun.planets

$sisyphus.pushRock()
## velocity assumes I mean $sisyphus.getRock()

$book.setTitle( "Homage to Catalonia" )
## Can't pass a parameter list



8. Formal Reference Notation


Shorthand notation for references was used for the examples listed above, but there is also a formal notation for references, which is demonstrated below:


레퍼런스의 속기 표기법이 위에 열거된 예들에서 사용되었지만, 밑에 쓰여있듯이 레퍼런스의 형식적 표기법 또한 있습니다:



${mudSlinger}
${customer.Address}
${purchase.getTotal()}


In almost all cases you will use the shorthand notation for references, but in some cases the formal notation is required for correct processing.


거의 모든 경우에서 당신은 레퍼런스를 위하여 속기 표기법을 사용할 것이지만, 어떤 경우에는 형식적 표기법이 정확한 프로세스를 위하여 필요합니다.


Suppose you were constructing a sentence on the fly where $vice was to be used as the base word in the noun of a sentence. The goal is to allow someone to choose the base word and produce one of the two following results: "Jack is a pyromaniac." or "Jack is a kleptomaniac.". Using the shorthand notation would be inadequate for this task. Consider the following example:


당신이 $vice가 문장안의 명사 중에서 기본적인 단어로로 사용되는 fly에 문장을 만든다고 가정합시다. 목표가 누군가가 기초적인 단어를 선택하고 뒤의 두가지 결과중 하나를 표현하도록 합니다.:" 잭은 방화광 입니다." 또한 "잭은 절도광입니다.". 속기 표기법을 사용하는 것은 이 작업에 대해 부적합했을 것입니다. 다음의 예에 대해 생각해봅시다:



Jack is a $vicemaniac.


There is ambiguity here, and velocity assumes that $vicemaniac, not $vice, is the Identifier that you mean to use. Finding no value for $vicemaniac, it will return $vicemaniac. Using formal notation can resolve this problem.


여기 애매한 점이 있어서 베로시티는 $vice가 아닌 $vicemaniac를 당신이 사용하려는 식별자로 가정합니다. $vicemaniac의 값를 찾지 못하면서, 다시 $vicemaniac으로 돌아갈 것입니다. 형식적 표기법을 사용하는 것은 이 문제를 해결할 수 있습니다 .



Jack is a ${vice}maniac.


Now velocity knows that $vice, not $vicemaniac, is the reference. Formal notation is often useful when references are directly adjacent to text in a template.


이제 베로시티는 $vicemaniac이 아닌 $vice가 레퍼런스라는 것을 알고 있습니다. 형식적 표기법은 레퍼런스들이 템플릿안에서 텍스트에 직접 붙어 있을 때 자주 유용하게 사용됩니다.



9. Quiet Reference Notation


When velocity encounters an undefined reference, its normal behavior is to output the image of the reference. For example, suppose the following reference appears as part of a VTL template.


베로시티에서 정의되지 않은 레퍼런스와 마주 치게 되면, 그것의 정상적인 행동은 결과에 레퍼런스의 결과의 이미지 입니다. 예를 들면, 다음의 레퍼런스가 VTL템플릿의 부분에 나타난다고 가정하시오.



<input type="text" name="email" value="$email" />


When the form initially loads, the variable reference $email has no value, but you prefer a blank text field to one with a value of "$email". Using the quiet reference notation circumvents velocity's normal behavior; instead of using $email in the VTL you would use $!email. So the above example would look like the following:


이런 형태가 처음에 적재 될 때, 변수 레퍼런스 $email 어떤 값을 가지고 있지 않습니다. 그러나 당신이 공백문자를 선호합니다. 가치를 가진 하나에의 필드 "$email". 숨겨진 레퍼런스 표기법을 사용하는 것이 베로시티의 정상적인 행동을 둘러쌉니다; VTL안에서 $email 사용하는 것 대신에 $!email 사용했을 것입니다. 그래서 위의 예가 다음과 같이 보였을 것입니다 :



<input type="text" name="email" value="$!email"/>


Now when the form is initially loaded and $email still has no value, an empty string will be output instead of "$email".


이런 형태가 처음에 저장되고 $email은 여전히 값을 가지고 있지 않았을때, "$email" 대신에 빈 문자열이 출력됩니다.


Formal and quiet reference notation can be used together, as demonstrated below.


형식적이고 숨겨진 레퍼런스의 표기법을 설명할 때 함께 사용될 수 있습니다.



<input type="text" name="email" value="$!{email}">



10. Cetting Literal


VTL uses special characters, such as $ and #, to do its work, so some added care should be taken where using these characters in your templates. This section deals with escaping the $character.


VTL은 그것을 작동시키기 하기 위하여 $와 # 같은 특별한 캐릭터들을 사용합니다. 그렇게 약간의 추가된 걱정이 당신의 템플릿안에서 이들 캐릭터들을 사용하면서 가져가져야 합니다. 이 부분은 $character escaping하는 것을 다룹니다.




  • Currency


There is no problem writing "I bought a 4lb. sack of potatoes at the farmer's market for only $2.50!" As mentioned, a VTL identifier always begins with an upper- or lowercase letter, so $2.50 would not be mistaken for a reference.


"나는 농부의 가게에서 단지 $2.50를 주고 4파운드의 감자를 샀습니다.!" 라고 쓰는 것은 전혀 문제가 없습니다. 언급되었던 것처럼, VTL 식별자는 항상 upper 또는 lower case 문자로 시작합니다, 그래서 $2.50는 레퍼런스와 관련하여 오해되지 않을 것입니다.




  • Escaping Valid VTL References


Cases may arise where there is the potential for Velocity to get confused. Escaping special characters is the best way to handle VTL's special characters in your templates, and this can be done using the backslash (\)character.


모든 경우에 베로시티는 혼란스럽게 될 잠재력이 있습니다. escaping special character는 당신의 템플릿안에서 VTL의 특별한 기호를 다루는데 가장 좋은 방법입니다. 그리고 이 방법은 backslash (\) 기호를 사용함으로써 행해질 수 있습니다.



#set( $email = "foo" )
$email


If Velocity encounters a reference in your VTL template to $email, it will search the Context for a corresponding value. Here the output will be foo. because $email is defined. If $email is not defined, the output will be $email.


베로시티가 당신의 $email이라는 VTL 템플릿안에서 레퍼런스를 마주친다면, 베로시티는 상응하는 값를 찾아 문맥을 검색할 것입니다. 여기서 $email이 정의되어 있기때문에 출력은 foo일 것입니다. 만약 $email이 정의되지 않아있다면 출력은 $email이 될 것입니다.


Suppose that $email is defined (for example, if it has the value foo), and that you want to output $email. There are a few ways of doing this, but the simplest is to use the escape character.


$email이 정의되어 있다는 것과(예를 들면, 그것이 값foo를 가지고 있다면) 당신이 $email을 출력하길 원한다고 가정합니다. 가정대로 하는 방법은 몇 가지 있지만, 가장 간단한 것은 escape character를 사용하는 것 입니다 .



## The following line defines $email in this template:
#set( $email = "foo" )
$email
\$email
\\$email
\\\$email


renders as



foo
$email
\foo
\$email


Note that the \character bind to the $ from the left. The bind-from-left rule causes \\\$email to render as \\$email. Compare these examples to those in which $email is not defined.


\기호가 $ 왼쪽에서 $를 묶는 것을 주목하십시오. bind-from-left규칙은 \\\$email이 \\$email을 출력하도록 합니다. 이들 예들을 $email이 정의되지 않은 예들과 비교를 해보십시오.



$email
\$email
\\$email
\\\$email


renders as



$email
\$email
\\$email
\\\$email


Notice Velocity handles references that are defined differently from those that have not been defined. Here is a set directive that gives $foo the value gibbous.


베로시티가 정의 되지 않은 것들로부터 다르게 정의된 레퍼런스들을 다룬다는 것을 명심하십시오. 여기에 $foo에 gibbous라는 값를 주는 set 명령어가 있습니다.



#set( $foo = "gibbous" )
$moon = $foo


The output will be:$moon = gibbous -- where $moon is output as a literal because it is undefined and gibbous is output in place of $foo.


출력은 다음과 같을 것입니다 : $moon = gibbous-- $moon이 문자그대로 출력되었습니다. 왜냐하면 $moon이 정의되지 않았고 gibbous가 $foo대신 출력되기 때문입니다


It is also possible to escape VTL directives; this is described in more detail in the Directives section.


VTL 명령어들을 회피하는 것 또한 가능합니다 ; 이것은 Directives section에서 좀더 자세하게 다루어집니다.



11. Case Substitution


Now that you are familiar with references, you can begin to apply them effectively in your templates. Velocity references take advantage of some Java principles that template designers will find easy to use. For example:


이제 당신은 레퍼런스를 친숙하게 당신의 템플릿안에서 효과적으로 응용 할 수 있습니다. 베로시티 레퍼런스은 템플릿 디자이너들이 쉽게 사용할 수 있도록 자바원칙들의 이점을 포함합니다. 예를 들면:



$foo

$foo.getBar()
## is the same as
$foo.Bar

$data.getUser("jon")
## is the same as
$data.User("jon")

$data.getRequest().getServerName()
## is the same as
$data.Request.ServerName
## is the same as
${data.Request.ServerName}


These examples illustrate alternative uses for the same references. Velocity takes advantage of Java's introspection and Bean features to resolve the reference names to both objects in the Context as well as the objects methods. It is possible to embed and evaluate references almost anywhere in your template.


이들 예들은 대안이 같은 레퍼런스들을 위하여 사용한다는 것을 설명합니다. 베로시티는 문맥안에 두 object의 레퍼런스 이름을 결정하는데 있어서 Java's introspection과 Bean feature 의 이점을 objects 매소드만큼 이용합니다. 당신의 템플릿안에서 거의 모든 곳에서 레퍼런스들을 끼워넣고 평가하는 것이 가능합니다.


Velocity, which is modelled on the Bean specifications defined by Sun Microsystems, is case sensitive; however, its developers have strove to catch and correct user errors wherever possible. When the method getFoo() is referred to in a template by $bar.foo, Velocity will first try $getfoo. If this fails, it will then try $getFoo.Similarly, when a template refers to $bar.Foo, Velocity will try $getFoo() first and then try getfoo().


Sun Microsystems에서 정의한 Bean specification에 의해 모델된 베로시티는 민감한 경우이다. 그러나 개발자들은 어느곳에서든 가능한한 에러를 찾아서 고치려고 노력해왔다. 메소드 getfoo()이 $bar.foo에 의해 템플릿안에서 언급될때, 베로시티는 첫 번째로 $getfoo를 시도할 것이다. 이것이 실패한다면, 그때는 $getFoo 를 시도할 것입니다. 유사하게, 템플릿이 $bar.Foo를 언급할때, 베로시티는 처음에 $getFoo()를 시도하고나서 getfoo()를 시도할 것입니다.


Note : References to instance variables in a template are not resolved. Only references to the attribute equivalents of JavaBean getter/setter methods are resolved (i.e.$foo.Name does resolve to the class Foo's getName() instance method, but not to a public Name instance variable of Foo).


Note: 템플릿안의 변수 사례를 위한 레퍼런스는 해결되지 않습니다. 단지 JavaBean getter/setter방법들의 속성 등가물들에의 레퍼런스들이 해결됩니다 (i.e.$ foo.Name이 class Foo's instance 메소드으로 바뀝니다. 그러나 public Name instance variable of Foo로는 바뀌지 않습니다).



12. Directives


References allow template designers to generate dynamic content for web sites, while directives -- easy to use script elements that can be used to creatively manipulate the output of Java code -- permit web designers to truly take charge of the appearance and content of the web site.


레퍼런스는 탬플릿 디자이너들이 웹 사이트의 다이나믹한 내용을 생성할 수 있도록 하는 반면, 명령어는--자바 코드의 출력을 창조적으로 다루는데 사용될 수 있는 script element를 사용하기에 쉬운-- 웹 디자이너들이 실제적으로 웹사이트의 appearance와 content를 관장하도록 합니다.

#set


The #set directive is used for setting the value of a eference. A value can be assigned to either a variable reference or a property reference, and this occurs in brackets, as demonstrated:


#set 명령어는 레퍼런스의 값을 정할 때 사용됩니다. 값은 변수 레퍼런스나 프로퍼디 레퍼런스 둘 모두에 할당될 수 있고, 이것은 아래에 보이는 것처럼 괄호 안에서 씁니다.



#set( $primate = "monkey" )
#set( $customer.Behavior = $primate )


The left hand side (LHS) of the assignment must be a variable reference or a property reference. The right hand side (RHS) can be one of the following types:


assinment의 left hand side (LHS)는 변수 레퍼런스 또는 프로퍼티 레퍼런스여야만 합니다. right hand side( RHS )는 다음의 타입들 중의 하나일 수 있습니다 :




  • Variable reference
  • String literal
  • Property reference
  • Method reference
  • Number literal
  • ArrayList


These examples demonstrate each of the aforementioned types:


밑의 예들이 위의 각 타입들을 보여줍니다 :



#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


NOTE : In the last example the elements defined with the [,,] operator are accessible using the methods defined in the ArrayList class. So, for example, you could access the first element above using $monkey.Say.get(0).


NOTE : 마지막 예에서 [,,]연산자로 정의된 element는 ArrayList class에서 정의된 메소드를 사용하여 이용하기 쉽습니다. 그래서 예를 들면, 당신은 앞에서 사용했던 $monkey.Say.get(0)을 이용해서 첫번째 element에 접근할 수 있습니다.


The RHS can also be a simple arithmetic expression:


또한 RHS는 간단한 수학적 표현도 가능합니다:



#set( $value = $foo + 1 )
#set( $value = $bar - 1 )
#set( $value = $foo * $bar )
#set( $value = $foo / $bar )


If the RHS is a property or method reference that evaluates to null, it will not be assigned to the LHS. It is not possible to remove an existing reference from the context via this mechanism. This can be confusing for newcomers to Velocity. For example:


만약 RHS가 프러퍼티또는 그 값이 null인 메소드 레퍼런스이라면, LHS로 할당되지 않을 것입니다. 문맥에서 현재의 레퍼런스를 이 매커니즘으로 제거하는 것은 가능하지 않습니다. 이런 점을 베로시티의 초보자들이 혼동 할 수 있습니다. 예를 들면 :



#set( $result = $query.criteria("name") )
The result of the first query is $result

#set( $result = $query.criteria("address") )
The result of the second query is $result


If $query.criteria("name") returns the string "bill",and $query.criteria("address") returns null, the above VTL will render as the following:


만약 $query.criteria("name")이 문자열 "bill로 return되고, $query.criteria("address")이 null로 return되면, 위 VTL는 아래와 같이 출력할 것입니다.



The result of the first query is bill

The result of the second query is bill


This tends to confuse newcomers who construct #foreach loops that attempt to #set a reference via a property or method reference, then immediately test that reference with an #if directive. For example:


이것은 property 또는 매소드 레퍼런스를 거쳐 #set 레퍼런스를 시도하는 #foreach 반복문을 만드는 초보자들을 혼동케하는 경향이 있습니다. 그때 즉시 그 레퍼런스를 #if 명령어를 가지고 시험합니다. 예를 들면:



#set( $criteria = ["name", "address"] )

#foreach( $criterion in $criteria )

#set( $result = $query.criteria($criterion) )

#if( $result )
Query was successful
#end

#end


In the above example, it would not be wise to rely on the evaluation of $result to determine if a query was successful. After $result has been #set (added to the context), it cannot be set back to null (removed from the context). The details of the #if and #foreach directives are covered later in this document


위의 예에서, query가 성공하였는지 결정하는데 있어 $result의 결과값에 의존하는 것은 현명하지 않을 것입니다. $result가 #set가 되어진후에(문맥에 덧붙여진), null로 다시 되돌릴 수 없습니다(문맥에서 제거된). #if와 #foreach 명령어의 세부사항들이 이 문서의 뒤에 다루어집니다.


One solution to this would be to pre-set $result to false. Then if the $query.criteria() call fails, you can check.


이것에의 하나의 해결책은 $reult를 false로 pre-set 하는 것 입니다. 그런다음 $query.criteria( ) call이 실패하면, 당신은 체크할 수 있습니다.



#set( $criteria = ["name", "address"] )

#foreach( $criterion in $criteria )

#set( $result = false )
#set( $result = $query.criteria($criterion) )

#if( $result )
Query was successful
#end

#end


Unlike some of the other Velocity directives, the #set directive does not have an #end statement.


몇몇의 다른 베로시티 명령어들과 다르게, #set 지령은 #end 문을 가지지 않습니다.

String Literals


When using the #set directive, string literals that are enclosed in double quote characters will be parsed and rendered, as shown:


#set을 사용할 때 quote character로 닫혀지는 string literal은 밑에 보인 것처럼 parse되고 출력될 것입니다.:



#set( $directoryRoot = "www" )
#set( $templateName = "index.vm" )
#set( $template = "$directoryRoot/$templateName" )
$template


The output will be


결과는



www/index.vm


However, when the string literal is enclosed in single quote characters, it will not be parsed:


하지만 string literal이 single quote characters일때는 parsed되지 않습니다 :



#set( $foo = "bar" )
$foo
#set( $blargh = '$foo' )
$blargh



bar
$foo


By default, this feature of using single quotes to render unparsed text is available in Velocity. This default can be changed by editing velocity.properties such that stringliterals.interpolate=false.


default에 의하여, 베로시티안에서 parse되지 않은 텍스트를 출력하기 위해 싱글 인용구를 사용하는 것은 가능하다. stringliterals.interpolate=false와 같은 velocity.properties를 편집하는 것에 의하여 이 default가 바뀔 수 있습니다.

Conditionals

12-3-1. If / ElseIf / Else


the #if directive in Velocity allows for text to be included when the web page is generated, on the conditional that the if statement is true. For example:


베로시티안의 #if 명령어는 문장이 참인 조건에서 웹페이지가 생성될때 포합될 텍스트를 허가합니다. 예를 들면



#if( $foo )
Velocity!
#end


The variable $foo is evaluated to determine whether it is true, which will happen under one of two circumstances: (i) $foo is a boolean (true/false) which has a true value, or (ii) the value is not null. Remember that the Velocity context only contains Objects, so when we say 'boolean', it will be represented as a Boolean (the class). This is true even for methods that return boolean - the introspection infrastructure will return a Boolean of the same logical value.


변수 $foo가 참인지 결정하기 위하여 평가됩니다. 이것은 두가지 상황 중에 하나의 상황이 일어날 것입니다: (i)$foo는 참인 값은 갖는 boolean(true/false)이거나 (ii) 값은 null이 아닙니다. 베로시티 문맥이 단지 Object을 포함한다는 것을 기억하십시오. 그래서 우리가 ' boolean' 이라고 말할 때, 그것은 Boolean (class)로 표현될 것입니다. 이것은 심지어boolean을 돌려주는 방법에서 조차 참입니다. introspection infrastructure는 어떤 논리 value의 Boolean로 되돌릴 것입니다.


The content between the #if and the #end statements become the output if the evaluation is true. In this case, if $foo is true, the output will be: "Velocity!". Conversely, if $foo has a null value, or if it is a boolean false, the statement evaluates as false, and there is no output.


#if 그리고 #end 사이에 들어있는 content가 참이면 결과가 나올 것입니다. 이 상황에서, $foo가 참이면, 결과가 있을 것입니다:" velocity!". 반대로, $foo가 null값을 가지면, 또한 그것이 boolean false이며, statement가 false로 평가하고, 그리고 어떤 결과가 없습니다.


An #elseif or #else element can be used with an #if element. Note that the Velocity Templating Engine will stop at the first expression that is found to be true. In the following example, suppose that $foo has a value of 15and $bar has a value of 6.


#elseif 또는 #else요소는 #if 요소와 함께 사용될 수 있습니다. 베로시티 템플릿 앤진는 참인 것으로 발견될 첫 번째 표현에서 멈출 것을 주의하시십오. 다음의 예안에서, $foo가 15의 값를 갖고 $bar이 6의 값을 갖는다고 가정합시다.



#if( $foo > 10 )
Go North
#elseif( $foo == 10 )
Go East
#elseif( $bar == 6 )
Go South
#else
Go West
#end


In this example, $foo is greater than 10, so the first two comparisons fail. Next $bar is compared to 6, which s true, so the output is Go South.


이 예에서, $foo가 10보다 크면 첫번째 두 비교들이 실패합니다. 다음 $bar이 6과 비교되어 참이고 그래서 결과는 "Go South"가 됩니다.


Please note that currently, Velocity's numeric comparisons are constrained to Integers - anything else will evaluate to false. The only exception to this is equality '==', where Velocity requires that the objects on each side of the '==' is of the same class.


일반적으로 것을 note하시오, 베로시티의 숫자의 비교는 정수들에 강요받게합니다. 그 어떤것도 false로 평가할것입니다. 이것에의 유일한 예외는 equality '==' 입니다. 베로시티의 '=='의 양쪽에 object가 같은 클래스 여야합니다.


Relational and Logical Operators Velocity uses the equivalent operator to determine the relationships between variables. Here is a simple example to illustrate how the equivalent operator is used.


베로시티는 변수들사이의 관계를 결정할 때 equivalent operator를 사용 합니다. 여기 equivalent operator가 어떻게 사용되는지 보여주는 간단한 예가 있습니다.



#set ($foo = "deoxyribonucleic acid")
#set ($bar = "ribonucleic acid")

#if ($foo == $bar)
In this case it's clear they aren't equivalent. So...
#else
They are not equivalent and this will be the output.
#end


Velocity has logical AND, OR and NOT operators as well. For further information, please see the VTL Reference Guide Below are examples demonstrating the use of the logical AND, OR and NOT operators.


베로시티는 논리 연산자 AND, OR, NOT 을 가지고 있습니다. 좀더 자세한 정보는 논리 연산자 AND, OR, NOT을 사용하는 방법의 예들인 VTL Reference Guide Below를 보십시오.



## logical AND

#if( $foo $bar )
This AND that
#end


The #if() directive will only evaluate to true if both $foo and $bar are true. If $foo is false, the expression will evaluate to false; $bar will not be evaluated. If $foo is true, the Velocity Templating Engine will then check the value of $bar; if $bar is true, then the entire expression is true and This AND that becomes the output. If $bar is false, then there will be no output as the entire expression is false.


#if()지령은 단지 $foo와 $bar 이 참인지만 평가할 것입니다. 만약 $foo 가 false라면, expression은 false로 평가할 것입니다 ;$bar는 평가되지 않을 것입니다. 만약 $foo가 참이라면, 베로시티 템플릿 엔진이 $bar의 값을 체크할 것입니다 ; 만약 $bar이 참이면, 그 때 전체 expression이 참이고 This And가 결과가 됩니다. $bar가 false라면, 그때 전체 expression이 false이므로 결과는 없을 것입니다.


Logical OR operators work the same way, except only one of the references need evaluate to true in order for the entire expression to be considered true. Consider the following example.


논리 연산자 OR도 같은 방법으로 작동합니다. 단지 레퍼런스중 하나가 전체 expression이 참으로 고려되기 위해 참을 평가할 필요가 있는 경우를 제외합니다. 다음의 예에 대해 생각해보십시오.



## logical OR

#if( $foo || $bar )
<strong>This OR That</strong>
#end


If $foo is true, the Velocity Templating Engine has no need to look at $bar; whether $bar is true or false, the expression will be true, and This OR That will be output. If $foo is false, however, $bar must be checked. In this case, if $bar is also false, the expression evaluates to false and there is no output. On the other hand, if $bar is true, then the entire expression is true, and the output is This OR That


만약 $foo가 참이라면, 벨로시티 템플릿 엔진이 $bar를 봐야할 필요는 없습니다; $bar 이 참이던 false 이던, expression은 참일 것이고, This OR That 은 출력될 것입니다. 만약 $foo가 false이라면, $bar을 체크해야 합니다. 이런 경우, 만약 $bar 또한 false라면, expression은 false로 평가하고 아무런 출려도 없습니다. 반면에, $bar 참이라면, 그때 전체 expression은 참입니다. 그리고 출력은 This OR That 입니다.



##logical NOT

#if( !$foo )
NOT that
#end


Here, the if $foo is true, then !$foo evaluates to false, and there is no output. If $foo is false, then !$foo evaluates to true and NOT tha will be output. Be careful not to confuse this with the quiet reference $!foo which is something altogether different.


여기서, $foo가 참이라면, 그 때 !$foo는 false로 평가하고, 아무런 출력이 없습니다. 만약에 $foo가 false라면, 그 때 !$foo는 참으로 평가하고 NOT가 출력될 것입니다. 이것을 완전하게 다른 quiet 레퍼런스와 혼동하지 않도록 조심하십시오.


Loops


The #foreach element allows for looping. For example :


#foreach element는 loop를 하도록 허용합니다. 예를 들면 :



<ul>
#foreach( $product in $allProducts )
<li>$product</li>
#end
</ul>


This #foreach loop causes the $allProducts list (the object) to be looped over for all of the products (targets) in the list. Each time through the loop, the value from $allProducts is placed into the $product variable.


#foreach loop는 $allProducts list(the object)가 list 안의 전체 product(target)에 대해 loop되도록 합니다. loop를 통한 각 시간, $allProduct으로 부터의 값은 $product 변수안에 위치합니다.


The contents of the $allProducts variable is a Vector, a Hashtable or an Array. The value assigned to the $product variable is a Java Object and can be referenced from a variable as such. For example, if $product was really a Product class in Java, its name could be retrieved by referencing the $product.Name method (ie:$Product.getName()).


$allProducts 변수의 content는 Vector, Hashtable 또는 Array입니다. $product 변수로 할당된 값는 자바 Object이고 such와 같은 변수들로부터 레퍼런스 될 수 있습니다. 예를 들면 ,만약 $product가 정말로 자바안에서 Product class 였다면, 그것의 이름은 $product.Name method ( ie :$ Product.getName ( ))을 레퍼런스 함으로써 검색될 수 있습니다.


Lets say that $allProducts is a Hashtable. If you wanted to retrieve the key value for the Hashtable as well as the objects within the Hashtable, you can use code like this:


$allProduct가 Hashtable이라고 합시다. 만약 당신이 Hashtable에서 object만 아닌 Hashtabl에서의 키값을 검색하려면, 당신은 이와 같이 코드를 사용할 수 있습니다 :



<ul>
#foreach( $key in $allProducts.keySet() )
<li>Key: $key -> value: $allProducts.get($key)</li>
#end
</ul>


Velocity provides an easy way to get the loop counter so that you can do something like the following:


베로시티는 당신이 아래와 같이 할 수 있도록 loop counter를 얻을 간단한 방법을 제공합니다 :



<table>
#foreach( $customer in $customerList )
<tr><td>$velocityCount</td><td>$customer.Name</td></tr>
#end
</table>


The default name for the loop counter variable reference, which is specified in the velocity.properties file, is $velocityCount.By default the counter starts at 1, but this can be set to either 0 or 1 in the velocity.properties file. Here's what the loop counter properties section of the velocity.properties


velocity.properties 파일안에서 명시되어있는, loop counter 변수 레퍼런스를 위한 default name은 $velocityCount입니다. default에 의하여 카운터가 1에서 시작하지만, 그러나 이것은 velocity.properties 파일안에서 0 이나 1둘 모두로 set 될 수 있습니다. 여기 loop counter properties section of the velocity.properties file이 무엇인지 나타나있습니다 :



# 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


Include


The #include script element allows the template designer to import a local file, which is then inserted into the ocation where the #include directive is defined. The contents of the file are not rendered through the template engine. For security reasons, the file to be included may only be under TEMPLATE_ROOT.


#include script element는 템플릿 디자이너가 local 파일을 끼워넣도록 허용합니다. 그때 local file은 #include 명령이 정의된 location에 삽입됩니다. 파일의 내용은 템플릿 엔진을 통해 받지 않습니다. 안전상의 이유로, 파일은 오직 TEMPLATE ROOT아래에 포함될 수 있습니다.



#include( "one.txt" )


The file to which the #include directive refers is enclosed in quotes. If more than one file will be included, they should be separated by commas.


#include 명령이 요청한 파일은 인용부호안에 싸여있습니다. 만약 하나 이상의 파일이 포함된다면, 콤마로 구분되어야 합니다.



#include( "one.gif","two.txt","three.htm" )


The file being included need not be referenced by name; in fact, it is often preferable to use a variable instead of a filename. This could be useful for targeting output according to criteria determined when the page request is submitted. Here is an example showing both a filename and a variable.


포함되어있는 파일은 이름에 의해 레퍼런스될 필요 없습니다 ; 실제로, 파일 이름대신에 변수를 사용하는 것은 바람직합니다. 이것은 page request가 요청될 때 결정되는 criteria에 따라 출력을 target 하는데 유용할 수 있습니다. 여기 파일이름과 변수모두를 보여주는 예가 있습니다 .



#include( "greetings.txt", $seasonalstock )


Parse


The #parse script element allows the template designer to import a local file that contains VTL. Velocity will parse the VTL and render the template specified.


#parse script element는 템플릿 디자이너가 VTL을 포함하는 local file을 끼워넣도록 허용합니다. 베로시티가 VTL을 분석하고 명기된 템플릿을 출력할 것입니다.



#parse( "me.vm" )


Like the #include directive, #parse can take a variable rather than a template. Any templates to which #parse refers must be included under TEMPLATE_ROOT. Unlike the #include directive, #parse will only take a single argument.


#include 명령처럼, #parse는 템플릿 이기보다는 변수를 취할 수 있습니다. #parse가 요청하는 어떤 템플릿이든 TEMPLATE_ROOT아래 포함되어야 합니다. #include 지령과 다르게, #parse 는 단지 single argument를 취할 것입니다.


VTL templates can have #parse statements referring to templates that in turn have #parse statements. By default set to 10, the parse_directive.maxdepth line of the velocity.properties allows users to customize maximum number of #parse referrals that can occur from a single template. (Note: If the parse_directive.maxdepth property is absent from the velocity.properties file, Velocity will set this default to 10.) Recursion is permitted, for example, if the template dofoo.vm contains the following lines:


VTL 템플릿은 #parse 문장을 가지고 있는 템플릿을 요청하는 #parse 문장을 가질 수 있습니다. 10으로 초기값을 설정함으로서, parse directive.maxdepth line of the velocity.properties은 사용자들이 템플릿 으로부터 발생할 수 있는 parse referral의 최대수를 최적화 할 수 있게 허용합니다. (Note : 만약 parse directive.maxdepth property 가 velocity.properties file 로부터 불려오지않는다면, 베로시티는 10에 초기값은 설정할 것입니다.) Recursion은 예를 들어, template dofoo.vm이 다음의 선들을 포함한다면 허락됩니다 :



Count down.
#set( $count = 8 )
#parse( "parsefoo.vm" )
All done with dofoo.vm!


It would reference the template parsefoo.vm, which might contain the following VTL:


그것이 다음의 VTL을 포함할지도 모르는 템플릿 parsefoo.vm을 레퍼런스 합니다.



#set( $count = $count - 1 )
#if( $count > 0 )
#parse( "parsefoo.vm" )
#else
All done with parsefoo.vm!
#end


After "Count down." is displayed, Velocity passes through parsefoo.vm, counting down from 8. When the count reaches 0, it will display the "All done with parsefoo.vm!" message. At this point, Velocity will return to dofoo.vm and output the "All done with dofoo.vm!" message.


"Count down." 다음에 보여집니다. 베로시티가 8부터 count down하면서 parsefoo.vm을 통과합니다. count가 0에 도달할 때, 그것은 "All done with parsefoo.vm!"라는 메세지를 보일 것입니다. 이 시점에서, 베로시티는 dofoo.vm으로 돌아가고 "All done with dofoo.vm!"라는 메시지를 출력할 것입니다.


Stop


The #stop script element allows the template designer to stop the execution of the template engine and return. This is useful for debugging purposes.


#stop script element는 템플릿 디자이너가 템플릿 엔진의 실행과 return을 멈추도록 허용합니다. 이것은 debugging purposes에 유용합니다.



#stop


Velocimacros


The #macro script element allows template designers to define a repeated segment of a VTL template. Velocimacros are very useful in a wide range of scenarios both simple and complex. This Velocimacro, created for the sole purpose of saving keystrokes and minimizing typographic errors, provides an introduction to the concept of Velocimacros.


#macrfo script element는 템플릿 디자이너들이 VTL 템플릿의 반복되는 문장을 정의하도록 허용합니다. Velocimacros는 간단하고 복잡한 시나리오 양쪽 모두의 넓은 범위에 매우 유용합니다. keystrokes를 저장하고 typographic error를 최소화하는 하나의 목적을 위하여 창조된, 이 Velocimacro는 Velocimacros의 개념에 대한 소개를 제공합니다.



#macro( d )
<tr><td></td></tr>
#end


The Velocimacro being defined in this example is d, and it can be called in a manner analogous to any other VTL directive:


이 예안에서 정의되는 Velocimacro는 d입니다. 그리고 그것은 다른 어떤 VTL 명령에 유사한 방법을 통해 불릴 수 있습니다 :



#d()


When this template is called, Velocity would replace #d() with a row containing a single, empty data cell.


이 템플릿이 불릴 때, 베로시티는 single, empty data cell을 포함하는 줄로 #d()를 대체합니다.


A Velocimacro could take any number of arguments -- even zero arguments, as demonstrated in the first example, is an option -- but when the Velocimacro is invoked, it must be called with the same number of arguments with which it was defined. Many Velocimacros are more involved than the one defined above. Here is a Velocimacro that takes two arguments, a color and an array.


Velocimacro는 argument의 수를 모두 취할 수 있습니다 - 심지어 첫번째 예에서 보여진 zero argument 조차 하나의 옵션입니다 - 그러나 Velocimacro가 불려질 때, 그것은 정의된 수만큼의 argument와 함께 불려야 합니다. 많은 Velocimacros는 위에서 정의된 하나보다 더 많이 관련됩니다. 여기 색과 array, 두 개의 argument를 취한Velocimacro가 있습니다.



#macro( tablerows $color $somelist )
#foreach( $something in $somelist )
<tr><td bgcolor=$color>$something</td></tr>
#end
#end


The Velocimacro being defined in this example, tablerows, takes two arguments. The first argument takes the place of $color, and the second argument takes the place of $somelist.


이 예안에서 정의되는 Velocimacro, tablerow는 두 개의 argument를 취합니다. 첫번째 argument는 $color 을 대체하고 두번째 argument는 $somelist를 대체합니다.


Anything that can be put into a VTL template can go into the body of a Velocimacro. The tablerows Velocimacro is a foreach statement. There are two #end statements in the definition of the #tablerows Velocimacro; the first belongs to the #foreach, the second ends the Velocimacro definition.


VTL 템플릿 안으로 넣어질 수 있는 것은 모두 Velocimacro의 안으로 갈 수 있습니다. tablerows Velocimacro는 foreach statement입니다. #tablerowsVelocimacro의 정의안에는 두개의 #end statement가 있습니다; 첫번째는 #foreach에 속하고, 두번째는 Velocimacro의 정의로 끝납니다.



#set( $greatlakes = ["Superior","Michigan","Huron","Erie","Ontario"] )
#set( $color = "blue" )
<table>
#tablerows( $color $greatlakes )
</table>


Notice that $greatlakes takes the place of $somelist. When the #tablerows Velocimacro is called in this situation, the following output is generated:


$greatlakes가 $somelist를 대체함을 주의하십시오. #tablerowsVelocimacro가 이런 상황에서 불려질때, 다음의 출력이 나옵니다 :



<table>
<tr><td bgcolor="blue">Superior</td></tr>
<tr><td bgcolor="blue">Michigan</td></tr>
<tr><td bgcolor="blue">Huron</td></tr>
<tr><td bgcolor="blue">Erie</td></tr>
<tr><td bgcolor="blue">Ontario</td></tr>
</table>


Velocimacros can be defined inline in a Velocity template, meaning that it is unavailable to other Velocity templates on the same web site. Defining a Velocimacro such that it can be shared by all templates has obvious advantages: it reduces the need to redefine the Velocimacro on numerous templates, saving work and reducing the chance of error, and ensures that a single change to a macro available to more than one template.


Velocimacros는 베로시티 템플릿안에서 inline으로 정의될 수 있습니다. 이것은 곧 같은 웹 사이트의 다른 베로시티 템플릿들에 적용할 수 없음을 의미합니다. Velocimacro이 모든 템플릿들에 공유될 수 있도록 정의하는 것에는 명백한 이점들이 있습니다 : 많은 템플릿들에서 Velocimacro를 재정의할 필요를 줄이고, 작업량을 줄이고 오류가 발생할 수 있는 기회를 줄이고, 그리고 하나보다 더 많은 템플릿에 이용 가능한 macro의 유일한 변화를 확실하게 합니다.


Were the #tablerows($color $list) Velocimacro defined in a Velocimacros template library, this macro could be used on any of the regular templates. It could be used many times and for many different purposes. In the template mushroom.vmdevoted to all things fungi, the #tablerows Velocimacro could be invoked to list the parts of a typical mushroom:


#tablerows($color $list) Velocimacro가 Velocimacros template library에서 정의되고, 이 macro는 모든 regular template들에서 사용될 수 있습니다. 또한 여러번, 많은 다른 목적을 위해 사용될 수 있습니다. 모든 fungi들의 template mushroom.vm 에서, #tablerows Velocimacro는 typical mushroom의 part 들 list로 요청될 수 있습니다 :



#set( $parts = ["volva","stipe","annulus","gills","pileus"] )
#set( $cellbgcol = "#CC00FF" )
<table>
#tablerows( $cellbgcol $parts )
</table>


When fulfilling a request for mushroom.vm, Velocity would find the #tablerows Velocimacro in the template library (defined in the velocity.properties file) and generate the following output:


mushroom.vm에 대한 요청을 이행할 때, 베로시티가 template library(velocity.properties file안에서 된)에서 #tablerows Velocimacro를 찾고 다음의 출력을 만듭니다 :



<table>
<tr><td bgcolor="#CC00FF">volva</td></tr>
<tr><td bgcolor="#CC00FF">stipe</td></tr>
<tr><td bgcolor="#CC00FF">annulus</td></tr>
<tr><td bgcolor="#CC00FF">gills</td></tr>
<tr><td bgcolor="#CC00FF">pileus</td></tr>
</table>


Velocimacro Arguments


Velocimacros can take as arguments any of the following VTL elements :


Velocimacros는 argument를 다음의 VTL element들 중 얼마든지 취할 수 있습니다 :




  • Reference : anything that starts with '$'
  • String literal : something like "$foo" or 'hello'
  • Number literal : 1, 2 etc
  • IntegerRange : [ 1..2] or [$foo .. $bar]
  • ObjectArray : [ "a", "b", "c"]
  • boolean value true
  • boolean value false


When passing references as arguments to Velocimacros, please note that references are passed 'by name'. This means that their value is 'generated' at each use inside the Velocimacro. This feature allows you to pass references with method calls and have the method called at each use. For example, when calling the following Velocimacro as shown


arguments to Velocimacros처럼 레퍼런스를 통과할때 레퍼런스가 'by name'으로 통과됨을 명심하십시오. 이것은 레퍼런스의 값이 Velocimacro안에서의 각각의 사용되에 'generated'임을 의미합니다. 이런 특징은 당신이 레퍼런스를 매소드를 요청하고 통과하게 하고 각 use에서 불려진 메소드를 가지게 허용합니다. 예를 들면, 보이는 바와 같이 다음의 Velocimacro를 부를 때



     #macro( callme $a )
$a $a $a
#end


results in the method bar() of the reference $foo being called 3 times.


method bar()안의 reference $foo가 세번 불려지는 출력을 합니다.


At first glance, this feature appears surprising, but when you take into consideration the original motivation behind Velocimacros -- to eliminate cut'n'paste duplication of commonly used VTL -- it makes sense. It allows you to do things like pass stateful objects, such as an object that generates colors in a repeating sequence for coloring table rows, into the Velocimacro.


첫번째 간단한 예에서, 이런 특징은 놀라워 보입니다. 그러나 당신이 Velocimacros의 진짜 동기를 고려할때 - 일반적으로 VTL에서 사용되는 cut'n'paste duplication을 제거하는 - 그것은 이치에 맞습니다. 이런 특징은 당신이 Velocimacro안으로, coloring table rows의 repeating sequence에서 color를 생성하는 object와 같은 stateful object를 pass하는 것과 같은 일을 하도록 합니다.


If you need to circumvent this feature, you can always just get the value from the method as a new reference and pass that :


당신이 이 특징을 circumvent한다면, 당신은 단지 새로운 레퍼런스와 같은 메소드로부터 값을 얻어서 pass할 수 있습니다 :



#set( $myval = $foo.bar() )
#callme( $myval )


Several lines in the velocity.properties file allow for flexible implementation of Velocimacros. Note that these are also documented in the Developer Guide.


velocity.properties file안의 여러줄들이 Velocimacros의 flexible implementation을 고려합니다. 이런 것들이 또한 Developer Guide 안에 기록되어 있음을 주의하십시오.


velocimacro.library - A comma-separated list of all Velocimacro template libraries. By default, Velocity looks for a single library:VM_global_library.vm. The configured template path is used to find the Velocimacro libraries.


velocimacro.library-A comma-모든 Velocimacro template libraries separated list. 초기치에 의하여, 베로시티가 하나의 library만을 찾습니다 : VM_global_library.vm.설정된 template path가 Velocimacro library를 찾는데 사용됩니다.


velocimacro.permissions.allow.inline - This property, which has possible value of true or false, determines whether Velocimacros can be defined in regular templates. The default, true, allows template designers to define Velocimacros in the templates themselves.


velocimacro.permissions.allow.inline- 참일수도 false일수도 있는 값을 가진 이 property는 Velocimacros가 regular template안에서 정의될 수 있는지를 결정합니다. 참인 초기값은 템플릿 디자이너들이 스스로 템플릿 안에서 Velocimacros를 정의하게 합니다.


velocimacro.permissions.allow.inline.to.replace.global- With possible value of true or false, this property allows the user to specify if a Velocimacro defined inline in a template can replace a globally defined template, one that was loaded on startup via the velocimacro.library property. The default, false, prevents Velocimacros defined inline in a template


velocimacro.permissions.allow.inline.to.replace.global-만약 inline template안에서 정의된 Velocimacro가 템플릿안에서 정의된 globally를 대체할 수 있다면, 참일 수도 거짓일 수도 있는 값을 가진 이 property는 velocimacro.library property의 startup에서 load 된 것을 명기하도로 합니다. 거짓 초기값은 inline template안에서 정의된 Velocimacros가 startup에서 load된 template library안에서 정의된 것들을 교체하는 것을 막습니다.


velocimacro.permissions.allow.inline.local.scope - This property, with possible value of true or false, defaulting to false, controls if Velocimacros defined inline are 'visible' only to the defining template. In other words, with this property set to true, a template can define inline VMs that are usable only by the defining template. You can use this for fancy VM tricks - f a global VM calls another global VM, with inline scope, a template can define a private implementation of the second VM that will be called by the first VM when invoked by that template. All other templates are unaffected.


velocimacro.permissions.allow.inline.local.scope- 참일수도 거짓일수도 있는 값을 가진 이 property는 거짓을 초기값으로 하면서 inline에서 정의된 Velocimacros가 정의하는 template에 대해 ' visible ' 인지 아닌지를 조절합니다. 다르게 말하면, 이 property를 갖고 참으로 set하면, 템플릿은 단지 정의하는 템플릿에 의해서만 유용한 inline VM을 정의할 수 있습니다. 당신은 이런 것을 fancy VM tricks에 대해 이용할 수 있습니다 - global VM 이 inline scope로 또다른 global VM 을 부른다면, 템플릿은 저 템플릿에 의해 불렸을 때 첫번째 VM에 의하여 불리워 질 두번째 VM의 private implementation을 정의할 수 있습니다. 다른 모든 템플릿들은 영향을 받지 않습니다.


velocimacro.context.localscope - This property has the possible value true or false, and the default is false. When true, any modifications to the context via #set() within a Velocimacro are considered 'local' to the Velocimacro, and will not permanently affect the context.


velocimacro.context.localscope- 이 property는 참일수도 거짓일수도 있는 값을 갖습니다. 그리고 초기값은 거짓입니다. 참일때는, Velocimacro를 통한 #set()로 문맥의 모든 modification이 Velocimacro에 대해 'local'로 고려됩니다. 그리고 문맥상 영구적으로 영향을 끼치지 않습니다.


When true, any modifications to the context via #set() within a Velocimacro are considered 'local' to the Velocimacro, and will not permanently affect the context. velocimacro.library.autoreload - This property controls Velocimacro library autoloading. The default value is false. When set to true the source Velocimacro library for an invoked Velocimacro will be checked for changes, and reloaded if necessary. This allows you to change and test Velocimacro libraries without having to restart your application or servlet container, just like you can with regular templates. This mode only works when caching is off in the resource loaders (e.g.file.resource.loader.cache = false ). This feature is intended for development, not for production.


velocimacro.library.autoreload-이 property는 autoloading하는 Velocimacro library를 조절합니다. 초기값은 거짓입니다. 참으로 설정할 때 요청된 Velocimacro에 대한 source Velocimacro library는 변화들에 대해 체크되고 필요하다면 reload 될 것입니다. 이것은 마치 당신이 regular template으로 할 수 있듯이, 당신의 application을 다시 시작하거나 servlet container할 필요없이 Velocimacro library를 바꾸고 테스트하도록 합니다. 이 모드는 오직 caching이 resource 안에서 off일때 작동합니다(e.g.file.resource.loader.cache = false). 이 특징은 production을 위한 것이 아닌 development를 위한 것입니다.


Velocimacro Trivia


Currently, Velocimacros must be defined before they are first used in a template. This means that your #macro() declarations should come before using the Velocimacros.


일반적으로 Velocimacros는 템플릿안에서 처음 이용되기 전에 정의되어야 합니다. 이것은 #macro() declaration이 Velocimacro를 이용하기 전에 와야 함을 의미합니다.


This is important to remember if you try to #parse() a template containing inline #macro() directives. Because the #parse() happens at runtime, and the parser decides if a VM-looking element in the template is a VM at parsetime, #parse()-ing a set of VM declarations won't work as expected. To get around this, simply use the velocimacro.library facility to have Velocity load your VMs at startup.


만약 당신이 inline #macro() 명령을 포함하는 #parse()템플릿이 시도한다면 앞내용을 기억하는 것은 중요합니다. 왜냐하면 #parse()가 runtime중에 발생하고, parser가 template 안에 VM-looking element 가 parsetime에 VM인지를 결정하고, 또한 #prase()-ing a set of VM declaration 은 기대한대로 작동하지 않을 것이기 때문입니다. 이런걸 여유있게 하기 위해서는, startup에서 VM을 load하는 베로시티를 가지도록 velocimacro.library facility 를 단순하게 사용하십시오.


Because the #parse() happens at runtime, and the parser decides if a VM-looking element in the template is a VM at parsetime, #parse()-ing a set of VM declarations won't work as expected.



Escaping VTL Directives


VTL directives can be escaped with the backslash character ("\") in a manner similar to valid VTL references.


valid VTL 레퍼런스와 유사한 방법으로, VTL 지령은 backslash 기호("\")를 사용하여 escape 될 수 있습니다.



## #include( "a.txt" ) renders as <contents of a.txt>
#include( "a.txt" )

## \#include( "a.txt" ) renders as \#include( "a.txt" )
\#include( "a.txt" )

## \\#include ( "a.txt" ) renders as \<contents of a.txt>
\\#include ( "a.txt" )


Extra care should be taken when escaping VTL directives that contain multiple script elements in a single directive (such as in an if-else-end statements). Here is a typical VTL if-statement:


single 명령어(if-else0end statement와 같은)안의 muliple script element를 포함하는 VTL 지령을 escape할 때는 특별히 주의를 기울여야 합니다. 전형적인 VTL if-statement가 여기 있습니다.



#if( $jazz )
Vyacheslav Ganelin
#end


If $jazz is true, the output is


만약 $Jazz가 참이면 결과는,


Vyacheslav Ganelin


If $jazz is false, there is no output. Escaping script elements alters the output. Consider the following case:


만약 $jazz가 거짓이 라면 결과는 없습니다. Escaping script elements는 결과를 바꿉니다. 다음의 경우를 생각하십시오 :



\#if( $jazz )
Vyacheslav Ganelin
\#end


Whether $jazz is true or false, the output will be.


$jazz가 참이거나 거짓이거나 결과는 존재합니다.



#if($ jazz )
Vyacheslav Ganelin
#end


In fact, because all script elements are escaped, $jazz is never evaluated for it's boolean value. Suppose backslashes precede script elements that are legitimately escaped:


사실상, 모든 script element가 escape되기 때문에, $jazz는 절대 boolean value로 평가되지 않습니다. backslashes가 적합하게 escape되는 script element 에 우선 한다고 가정하십시오:



\\#if( $jazz )
Vyacheslav Ganelin
\\#end


In this case, if $jazz is true, the output is


이 경우에 만약 $jazz가 참이면 결과는



\ Vyacheslav Ganelin
\


To understand this, note that the #if(arg)when ended by a newline (return) will omit the newline from the output. Therefore, the body of the #if() block follows the first '\', rendered from the '\\' preceding the #if(). The last \ is on a different line than the text because there is a newline after 'Ganelin', so the final \\, preceding the #end is part of the body of the block.


이것을 이해하기 위해서는, newline(return)으로 끝나질 때의 #if(arg)는 결과로부터 newline을 뺄 것입니다. 그래서, #if() block의 body 는 #if()에 선행되는 '\\' 로부터 오는 첫 '\'를 따릅니다. 'Ganelin' 다음의 newline 이 있기 때문에 마지막 \는 text 보다 다른 line에 있습니다. 그래서 #end에 선행하는 마지막 \\ 는 block 의 body 의 일부분입니다.


If $jazz is false, there is no output. Note that things start to break if script elements are not properly escaped


만약 $jass가 거짓이면, 결과는 없습니다. script element가 적당히 escape되지 않는다면 여러가지가 break하기 시작함을 주의하십시오.



\\\#if( $jazz )
Vyacheslave Ganelin
\\#end


Here the #if is escaped, but there is an #end remaining; having too many endings will cause a parsing error.


여기 #if가 escape되지만, 하나의 #end 가 남아있습니다; 너무 많은 end를 갖는것은 parsing error를 유발할 것입니다 .



14. VTL : Formatting Issues


Although VTL in this user guide is often displayed with newlines and whitespaces, the VTL shown below


이 사용자 가이드안의 VTL이 종종 newlines과 whitespaces를 가지고 보여지지만, 밑에 보이는 VTL은



#set( $imperial = ["Munetaka","Koreyasu","Hisakira","Morikune"] )
#foreach( $shogun in $imperial )
$shogun
#end


is equally valid as the following snippet that Geir Magnusson Jr. posted to the Velocity user mailing list to illustrate a completely unrelated point


Geir Magnusson Jr.가 베로시티사용자 우편list로 완전히 언급되지 않은점을 설명하기 위하여 부쳤던 다음의 snippet과 같이 타당합니다 :



Send me #set($foo = ["$10 and ","a cake"])#foreach($a in $foo)$a #end please.


Velocity's behaviour is to gobble up excess whitespace. The preceding directive can be written as:


베로시티의 반응은 과잉 whitespace를 gobble up하는 것 입니다. 선행하는 지령은 다음과 같이 쓰일 수 있습니다 :



Send me
#set( $foo = ["$10 and ","a cake"] )
#foreach( $a in $foo )
$a
#end
please.


or as



Send me
#set($foo = ["$10 and ","a cake"])
#foreach ($a in $foo )$a
#end please.



In each case the output will be the same.


각 경우에서 결과는 같을 것입니다.



15. Other Features and Miscellany


Math


Velocity has a handful of built-in mathematical functions that can be used in templates with the set directive. The following equations are examples of addition, subtraction, multiplication and division, respectively:


베로시티는 set directive를 가지고 템플릿들에서 사용될 수 있는 붙박이 수학적인 기능들을 한 웅큼을 가지고 있습니다. 다음의 식들은 각각 , 덧셈,뺄셈, 곱샘 그리고 나눗셈이 예들입니다.



#set( $foo = $bar + 3 )
#set( $foo = $bar - 4 )
#set( $foo = $bar * 6 )
#set( $foo = $bar / 2 )


When a division operation is performed, the result will be an integer. Any remainder can be obtained by using the modulus (%) operator.


나누기 계산이 수행될 때, 결과는 정수일 것입니다. modulus(%) 연산자를 사용하는 것에 의하여 어느정도의 나머지가 습득될 수 있습니다.



#set( $foo = $bar % 5 )


Only integers (...-2, -1, 0, 1, 2...) are permissible when performing mathematical equations in Velocity; when a non-integer is used, it is logged and a null will be returned as the output.


오직 정수(,,,-2, -1, 0, 1, 2,,,)가 베로시티에서 mathematical equations를 수행할때 허용할수 있다; 비정수가 사용될때, log되고 null은 결과로 대체된다.


Range Operator


The range operator can be used in conjunction with #set and #foreach statements. Useful for its ability to produce an object array containing integers, the range operator has the following construction:


범위 연산자는 #set과 #foreach statements를 가진 결합안에서 이용될 수 있습니다. 그것의 능력이 물체 배열을 생산하기에 유용하게 완전체들을 포함합니다. 범위연산자는 다음의 구조를 가지고 있습니다 :



[n..m]


Both n and m must either be or produce integers. Whether m is greater than or less than n will not matter; in this case the range will simply count down. Examples showing the use of the range operator as provided below:


n과 m둘다 존재하기 보다는 정수를 산출합니다. m이 큰지 n이 작은지는 문제가 되지 않습니다.; 이 경우 범위가 간단히 카운트다운할 것입니다. 예들 밑에서 대비한 것으로서 range operator의 사용을 보여줍니다 :



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]


Produces the following output:



First example:
1 2 3 4 5

Second example:
2 1 0 -1 -2

Third example:
0 1

Fourth example:
[1..3]


Note that the range operator only produces the array when used in conjunction with #set and #foreach directives, as demonstrated in the fourth example.


4번째 예에서 range operator가 #set과 #foreach를 가지고 결합하여 사용할때 단지 배열을 생산하는 걸 note하시오.


Web page designers concerned with making tables a standard size, but where some will not have enough data to fill the table, will find the range operator particularly useful.


웹 페이지 디자이너들은 테이블들을 표준 크기로 만드는 것을 관여했습니다. 그러나 어떤 테이블은 채우기에 충분한 데이타를 가지고 있지 않을 것이고, 특별히 유용한 range operator를 발견할 것입니다.


Advanced Issues: Escaping and !


When a reference is silenced with the ! character and the ! character preceded by an \ escape character, the reference is handled in a special way. Note the differences between regular escaping, and the special case where \ precedes ! follows it:


레퍼런스가 조용하게 될 때 ! 캐릭터 그리고 ! 캐릭터가 \ escape character에 의해 앞서게 됩니다. 레퍼런스가 특별한 방법안에서 다루어집니다. regular escapng과 \ 가 그것의 !를 선행하는 특별한 케이스의 차이점을 노트하시오;



#set( $foo = "bar" )
$\!foo
$\!{foo}
$\\!foo
$\\\!foo


This renders as:



$!foo
$!{foo}
$\!foo
$\\!foo


Contrast this with regular escaping, where \ precedes $:


\가 $를 선행하는regular escaping를 가진 이것을 대조하라:



\$foo
\$!foo
\$!{foo}
\\$!{foo}


This renders as:



\$foo
\$!foo
\$!{foo}
\bar


Velocimacro Miscellany


This section is a mini-FAQ on topics relating to Velocimacros. This section will change over time, so it's worth checking for new information from time to time.


Velocimacros와 친하게 지내면서 이 부분이 화제들위에 mini-FAQ 입니다. 때때로 새로운 정보를 위하여 조사하면서 이 부분이 시간내내 변할 것이고, 그렇게 그것은 가치가 있습니다.


Note : Throughout this section, 'Velocimacro' will commonly be abbreviated as 'VM'.


Note : 이 부분 전체에, 'Velocimacro' 는 일반적으로 'VM' 으로 단축하여 사용합니다


Can I use a directive or another VM as an argument to a VM?


Example : #center( #bold("hello") )


No. A directive isn't a valid argument to a directive, and for most practical purposes, a VM is a directive.


아니오. 지령은 지령에 타당한 논쟁이 아닙니다. 그리고 가장 가장 실용적인 목적들을 위하여, VM은 지령입니다.


there are things you can do. One easy solution is to take advantage of the fact that 'doublequote' (") renders it's contents. So you could do something like.


당신이 할 수 있는 것들이 있습니다. 하나의 간단한 해결책은 사실의 이점을 가져가는 것 입니다 'doublequote'(") 그것을 주고 내용들 입니다. 그래서 당신이 무언가를 할 수 있었습니다.



#set($stuff = "#bold('hello')" )
#center( $stuff )


You can save a step...


당신은 step을 save 할수 있습니다.



#center( "#bold( 'hello' )" )


Please note that in the latter example the arg is evaluated inside the VM, not at the calling level. In other words, the argument to the VM is passed in in its entirety and evaluated within the VM it was passed into. This allows you to do things like :



#macro( inner $foo )
inner : $foo
#end

#macro( outer $foo )
#set($bar = "outerlala")
outer : $foo
#end

#set($bar = 'calltimelala')
#outer( "#inner($bar)" )


Where the output is



Outer : inner : outerlala


because the evaluation of the "#inner($bar)" happens inside #outer(), so the $bar value set inside #outer() is the one that's used.


This is an intentional and jealously guarded feature - args are passed 'by name' into VMs, so you can hand VMs things like stateful references such as


이것은 의도적이고 질투하여 신중한 특징 입니다 - args는 통과됩니다 ' 이름에 의하여' VMs안으로, 당신은 stateful 레퍼런스들과 같이 VMs 사물들을 건네줄 수 있습니다.



#macro( foo $color )
<tr bgcolor=$color><td>Hi</td></tr>
<tr bgcolor=$color><td>There</td></tr>
#end

#foo( $bar.rowColor() )


And have rowColor() called repeatedly, rather than just once. To avoid that, invoke the method outside of the VM, and pass the value into the VM.


그리고 rowColor()는 한번이 아니라 계속적으로 요청 되어진다.



#set($color = $bar.rowColor())
#foo( $color )


Can I register Velocimacros via #parse()? Currently, Velocimacros must be defined before they are first used in a template. This means that your #macro() declarations should come before using the Velocimacros.


일반적으로, Velocimacros는 그들이 첫번째로 템플릿안에서 이용되기전에 선언되어져야 합니다. 이것은 Velocimacro를 사용하기 전에 당신의 #macro() 의 선언들이 와야 함은 의미합니다.


This is important to remember if you try to #parse() a template containing inline #macro() directives. Because the #parse() happens at runtime, and the parser decides if a VM-looking element in the template is a VM at parsetime, #parse()-ing a set of VM declarations won't work as expected. To get around this, simply use the velocimacro.library facility to have Velocity load your VMs at startup.


만약 당신이 #macro명령줄에 #parse()를 포함시키려했다면 중요한 것을 기억하야합니다. 왜냐하면 #parse()는 runtime이 일어나고,


Because the #parse() happens at runtime, and the parser decides if a VM-looking element in the template is a VM at parsetime, #parse()-ing a set of VM declarations won't work as expected.


What is Velocimacro Autoreloading?


There is a property, meant to be used in development, not production :


prduction이 아닌 development안에서 사용됨은 의미하는 property가 있습니다.:


(where <type> is the name of the resource loader that you are using, such as 'file') then the Velocity engine will automatically reload changes to your Velocimacro library files when you make them, so you do not have to dump the servlet engine (or application) or do other tricks to have your Velocimacros reloaded.


(<type>는 파일과 같이 당신이 사용하는 loader의 이름은 있습니까) 베로시티 엔진은 당신의 Velocimacro library files 변화를 자동으로 다시 load할 것입니다. 그렇게 당신은 servlet엔진을 덤핑하지 말아야 합니다.(또한 application ), 또 당신의 Velocimacros를 다시 load 할 다른 트릭들을 보냅니다.


Here is what a simple set of configuration properties would look like.


배열 property들의 간결한 세트가 보이는 것은 여기 있습니다 .


file.resource.loader.path = templates file.resource.loader.cache = false velocimacro.library.autoreload = true Don't keep this on in production.


String Concatenation


A common question that developers ask is How do I do String concatenation? Is there any analogue to the '+' operator in Java?


개발자들이 물어보는 일반적인 질문은 "어떻게 문자열을 연결하지?" "자바안에서 덧셈 연산자의 아날로그가 거기 있습니까?"


To do concatenation of references in VTL, you just have to 'put them together'. The context of where you want to put them together does matter, so we will illustrate with some examples.


VTL안에서 레퍼런스들의 연결 하기 위하여, 당신이 단지 'put them together" 합니다. 당신이 함께 그것을 놓기를 원했는지의 문맥이 문제되기때문에, 그래서 우리는 약간의 예들을 가지고 설명할 것입니다 .


In the regular 'schmoo' of a template (when you are mixing it in with regular content) :


템플릿의 'schmoo'규칙안에서 (당신이 규칙적인 내용에 'schmoo'섞을 때):



#set( $size = "Big" )
#set( $name = "Ben" )

The clock is $size$name.


and the output will render as 'The clock is BigBen'. For more interesting cases, such as when you want to concatenate strings to pass to a method, or to set a new reference, just do


그리고 결과는 'The clock is BigBen'일 것입니다. 언제 당신이 연결된 문자열 메소드에 pass를 원할때 더 흥미있는 경우들을 위하여, 또한 새로운 레퍼런스를 단지 set 하는 것.



 #set( $size = "Big" )
#set( $name = "Ben" )

#set($clock = "$size$name" )

The clock is $clock.


Which will result in the same output. As a final example, when you want to mix in 'static' strings with your references, you may need to use 'formal references' :


그것이 같은 결과를 초래할 것입니까. 마지막 예에서, 당신이 'static' 안에 섞이기를 원한다면 당신의 레퍼런스들을 가진 문자열, 당신은 형식적 레퍼런스를 사용할 필요가 있을 수 있습니다.



 #set( $size = "Big" )
#set( $name = "Ben" )

#set($clock = "${size}Tall$name" )

The clock is $clock.


Now the output is 'The clock is BigTallBen'. The formal notation is needed so the parser knows you mean to use the reference '$size' versus '$sizeTall' which it would if the '{}' weren't there.


결과는 'The clock is BigTallEen'입니다. 형식적 표기법은



16. Feedback


If you encounter any mistakes in this manual or have other feedback related to the Velocity User Guide, please email the Velocity user list. Thanks!


당신이 이 메뉴얼에서 어떤 실수들을 하거나, 다른 피드백을 베로시티 사용자 가이드에 관련시켜고자 한다면, Velocity user list로 email을 보내시오. 감사합니다 !



[바로가기 링크] : http://coolx.net/cboard/develop/546


Name
Password
Comment
Copyright © 1999-2017, swindler. All rights reserved. 367,611 visitor ( 1999.1.8-2004.5.26 ), 2,405,771 ( -2017.01.31)

  2HLAB   2HLAB_Blog   RedToolBox   Omil   Omil_Blog