Velocity

Velocityについて

コミュニティ

ドキュメント

ツール

比較

日本語訳について

Table of Contents − 目次
  1. About this Guide
  2. What is Velocity?
  3. What can Velocity do for me?
    1. The Mud Store example
  4. Velocity Template Language (VTL): An Introduction
  5. Hello Velocity World!
  6. Comments
  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. このガイドについて
  2. Velocityとは?
  3. Velocity で何ができるの?
    1. Mud Store のサンプル
  4. Velocity テンブレート言語 (VTL): はじめに
  5. Hello Velocity World!
  6. コメント
  7. リファレンス
    1. 変数
    2. プロパティ
    3. メソッド
  8. 正式リファレンス表記
  9. 沈黙リファレンス表記
  10. リテラルを取得する
    1. 通貨
    2. 有効なVTL リファレンスをエスケープする
  11. 大文字小文字置換
  12. 指示子
    1. #set
    2. 文字列リテラル
    3. if-else 文
      1. 関係演算子と論理演算子
    4. #foreach ループ
    5. #include
    6. #parse
    7. #stop
    8. Velocimacro
  13. VTL 指示子をエスケープする
  14. VTL のフォーマット
  15. その他の機能
    1. Math
    2. 範囲演算子
    3. 高度な問題: エスケープと「!」
    4. Velocimacro いろいろ
    5. 文字列の連結
  16. フィードバック


About this Guide − このガイドについて

The Velocity User Guide 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.

Velocity ユーザガイドは、ページデザイナやコンテンツ・プロパイダに Velocity と、 Velocity の単純ながらも強力なスクリプト言語である Velocity テンプレート言語 (VTL:Velocity Template Language) の構文を理解していただくことを目的としています。 このガイドで出てくる例の多くは、Web サイトで動的に内容を埋め込むための Velocity の使い方を扱っていますが、VTL の例はすべて、 その他のページやテンプレートにも同様に適用できます。

Thanks for choosing Velocity!

Velocity を選んでいただきありがとうございます。


What is Velocity? − Velocityとは?

Velocity is a Java-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.

Velocity は、Java ベースのテンプレートエンジンです。 Velocityを使うと、Web ページデザイナが Java コードで定義されたメソッドを参照できます。Model-View-Controller(MVC) モデルに基づく Web サイト開発で、 Java プログラマと Web デザイナが並行して作業できます。つまり、 Web ページデザイナは素晴らしいデザインのサイトをつくることだけに集中し、 プログラマは最高のコードを書くことだけに集中できるということです。 Velocity は、Java コードを Web ページから切り離し、長い目で見ればより保守しやすい Web サイトを実現し、 Java Server Pages(JSP) や PHP の実現可能な代替案を提供します。

Velocity 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.

Velocity は Web ページや SQL、PostScript といった出力をテンプレートから生成するのに 使えます。ソースコードや帳票を生成する単体のユーティリティとしても使えますし、 他のシステムに統合されるコンポーネントとしても使えます。 Velocityは、Turbine Web アプリケーションフレームワークでテンプレートサービスを提供します。 Velocity と Turbine の組み合わせで、真の MVC モデルにしたがって Web アプリケーションを開発できるテンプレートサービスを提供します。


What can Velocity do for me? − Velocity で何ができるの?
The Mud Store Example − Mud Store のサンプル

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?

あなたが陶土を専門に扱うオンラインストアのページデザイナであるとしましょう。 オンラインストアの名前は「Online Mud Store」としましょう。 商売は繁盛しています。顧客はいろいろな種類や量の商品を発注します。 サイトにはユーザー名とパスワードを使用してログインし、 注文内容を確認したり、さらに商品を購入したりできます。 現在、テラコッタ土 [訳注:素焼き用の陶土] はセール中で、とても人気があります。 赤土もセール中ですが、あまり人気が無く、少数の顧客が定期的に買うぐらいで、 いつもは Web ページの片隅に追いやられています。 各顧客に関する情報 [購買履歴など] はデータベースに記録されます。 そんなある日、こんな疑問が湧きます。「特別セールを行う時に、 セール対象の商品に最も興味を持っている顧客をターゲットとするのに Velocity を使うのはどうだろう?」

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.

Velocity なら、オンライン訪問者ごとに Web ページを簡単にカスタマイズできます。 「The Mud Room」の Web サイトデザイナであるあなたは、顧客がサイトログイン後に見る Web ページを作ろうと思っています。

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 オブジェクトには、宣伝に役立つメソッドが入っています。 当面の作業では、これらの3つのリファレンスにだけ注目しましょう。 ソフトウェアエンジニアがどのように必要な情報をデータベースから抽出するかについては 気にしなくてよく、 その情報が使えることだけ知っていればよいということ注目してください。 つまり、あなたもソフトウェアエンジニアも、自分の仕事にだけ注力できるということです。

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

以下の VTL 文を Web ページに埋め込みます。

<HTML>
<BODY>
Hello $customer.Name!
<table>
#foreach( $mud in $mudsOnSpecial )
   #if ( $customer.hasPurchased($mud) )
      <tr>
        <td>
          $flogger.getPromo( $mud )
        </td>
      </tr>
   #end
#end
</table>
</BODY>

The 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 limited only by your creativity.

foreach 文の詳細は後段で説明しますが、 ここで重要なのは、この短いスクリプトがあなたの Web サイトにあたえるインパクトです。 赤土を好む顧客がログインしたとき、赤土がセール中であれば、 この顧客向けに、赤土がセール中であることを特に目につくように表示します。 テラコッタ土購入歴の長い顧客がログインしたときには、 テラコッタ土のセールのお知らせを一番目立つ場所に表示します。 Velocityの柔軟性は極めて高く、あとはあなたの創造力次第です。

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リファレンスでは、その他にもたくさんの Velocity 要素が記述されており、 これらを組み合わせることで、 Web サイトの存在感 を高めるのに必要なパワーと柔軟性が得られます。 これらの要素に詳しくなれば、Velocity のパワーをさらに発揮できるでしょう。



Velocity Template Language (VTL): An Introduction − Velocity テンブレート言語 (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.

Velocity テンプレート言語(VTL:Velocity Template Language) は、 Web ページに動的な内容を取り込むのに最も簡単、単純で、 無駄のない方法となることを目標としています。 ほとんどプログラミング経験のない Web ページ開発者でも、 VTL を使えばすぐに、動的な内容を Web サイトに取り込めるようになるはずです。

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 では Web サイトにおいて動的な内容を埋め込むのにリファレンス を使いますが、 変数はその一種です。変数とは Java コードで定義したものを参照するリファレンスの一種で、 Web ページ内の 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 という指示子を含みます。 Webページが要求されたとき、Velocity テンプレートエンジンは Web ページを走査して全ての 「#」を見つけ、 それぞれについて、どれが 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 指示子は、(括弧で囲まれた)式 ─ 変数 を割り当てる 等式 ─ を使います。変数は左側で値は右側になります。この2つは、「=」で区切られます。

In the example above, the variable is $a and the value is Velocity. This variable, like all references, begins with the $ character. Values 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 です。 全てのリファレンスがそうであるように、この変数は 「$」で始まります。 値は常に引用符で囲まれます。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.

以下の簡単なルールが、Velocity がどのように動作するかをさらに理解するのに役立つでしょう。 リファレンスは、「$」 から始まって、何かを取得するのに使います。 指示子は、「#」 から始まって、何かを行うのに使います。

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) は、「Velocity」を出力するのにテンプレートで使うことができます。


Hello Velocity World! − Hello Velocity World!

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 に割り当てられて後で参照されます。

<html>
<body>
#set( $foo = "Velocity" )
Hello $foo World!
</body>
<html>

The result is a web page that prints "Hello Velocity World!".

結果として Web ページは、"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 指示子については、後ほど更に詳しく説明します。


Comments − コメント

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.

一行コメントは、## で始まり行末で終わります。 コメントを複数行書こうとする場合、一行コメントをたくさん並べる必要ありません。こういう場合には、 複数行コメント (#* で始まり *# で終わります) が利用できます。

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.
この部分は複数行コメントの外なので、
ページには表示されます。

#*
 複数行コメントはここからです。ページにはこのテキストは表示されません。
 Velocity テンプレートエンジンはこの部分を無視するからです。
*#

ここも複数行コメントの外なので、ページに表示されます。

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

一行コメントと複数行コメントの動作を分かりやすく説明するいくつかの例を以下に示します。

This text is visible. ## 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:

コメントには第3の形式 (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
*#
#**
これは VTL コメントブロックで、
文書の作者やバージョン情報といった
情報を格納するのに使われるかも
しれません。
@author
@version 5
*#


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 には、変数/プロパティ/メソッドという3種類のリファレンスがあります。 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という名前のオブジェクト (例えばIntegerオブジェクト) があるならば、 Velocity はオブジェクトを文字列にするために.toString()メソッドを呼びます。

Variables
The 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 the characters are limited to the following types of characters:

変数
変数の簡略表記は、「$」とそれに続く VTL 識別子 から構成されます。 VTL 識別子は、英字から始めなければなりません (a・・・zまたはA・・・Z)。 先頭以外の文字についても、以下の種類に限定されます:

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

  • アルファベット (a・・・z, A・・・Z)
  • 数字 (0・・・9)
  • ハイフン ("-")
  • アンダースコア ("_")

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 指示子、 または Java のコードから取得できます。 例えば、テンプレートが要求された時に Java 変数 $foo が値 bar を持っていれば、Web ページ上で $foo の全てのインスタンスが bar で置換できます。言い換えると、以下の文を入れると、

#set( $foo = "bar" )

The output will be the same for all instances of $foo that 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 識別子、それにドット「.」を挟んで続く別の VTL 識別子から成ります。 VTL での有効なプロパティリファレンスの例を示します:

$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 be 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) の場合は、2つの意味が考えられます。 一つは、customer で識別される hashtable を見て、 キー Address と関連づけられる値を返すという意味です。 しかし、$customer.Address はメソッドを参照しているのかも知れないのです。 (メソッドを参照するリファレンスは、次のセクションで説明します)。 $customer.Address は、$customer.getAddress() の省略表記でもあるのです。 ページが要求されたとき、Velocity はこれらの2つの可能性のうち どちらが意味をなすかを判定して、適切な値を返します

Methods
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:

メソッド
メソッドは Java コードにおいて定義されるもので、何か役に立つこと (計算や判定の実行など) を行うことができます。 メソッドは「$」と、それに続く VTL 識別子と、それに続く VTL メソッドボディ (Method Body) から構成されるリファレンスです。 VTL メソッドボディは、VTL 識別子と、それに続く左括弧("(")、 パラメータリスト (オプション)、それに右括弧(")")から構成されます。 VTL で有効なメソッドリファレンスの例を示します。

$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!

最初の2つの例 ($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 メソッドの簡略表記として使えます。 プロパティ $customer.Address は、 メソッド $customer.getAddress() を使うのと完全に同じ効果があります。 一般に、利用可能ならプロパティを使う方が望ましいです。 プロパティとメソッドの主な違いは、 メソッドにはパラメータリストを指定できるということです。

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
$sun.getPlanet( ["Earth", "Mars", "Neptune"] )
## $sun.Planets にはパラメータリストを渡せません。

$sisyphus.pushRock()
## ($sisyphus.Rockだと) Velocity は $sisyphus.getRock() だと思ってしまいます。

$book.setTitle( "Homage to Catalonia" )
## パラメータリストは渡せません。

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 を使うとしましょう。誰かにベースとなる単語を選択させて、 「Jack is pyromaniac.」あるいは「Jack is kleptomaniac.」という結果を生成します。 こういう場合、簡略表記を使用するとまずいのです。 以下の例を考えてみてください。

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.

この表現は曖昧で、Velocity は識別子として、あなたが使いたい$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.

こうすれば Velocity は、$vicemaniac ではなく $vice がリファレンスであると認識します。 正式表記が役に立つことが多いのは、 このようにリファレンスがテンプレート中でテキストと隣接している時です。

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.

沈黙リファレンス表記
Velocity が未定義のリファレンスに遭遇したとき、 通常の挙動として、リファレンスの記述をそのまま出力します。 例えば、以下のリファレンスが 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」という値が入っているより ブランクになっている方がよいでしょう。 リファレンスの沈黙表記を使用することで、Velocity の通常の挙動を回避します。 具体的には 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}"/>


Getting 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 は、「$」 や 「#」のように特殊文字を使用するので、 テンプレート内でこれらの文字を使用する場合には注意が必要です。 このセクションでは、「$」をエスケープする方法を説明します。

Currency
There is no problem writing "I bought a 4 lb. 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.

通貨
「私は市場で 4ポンドの袋入りのジャガイモをたった $2.50 で買いました!」 と書くことについては問題はありません。 VTL 識別子は常に大文字または小文字の英字から始まるので、$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.

有効なVTLリファレンスをエスケープする
Velocity が混乱する可能性がある場合もあります。 特殊文字のエスケープは、テンプレート内で VTL の特殊文字を扱う最適な方法であり、 バックスラッシュ(\)を使って行えます。

#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.

Velocity が VTL テンプレートで $email リファレンスを検出すると、 対応する値を求めてコンテキストを検索します。 ここでは、$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.

(例えば値が foo である) $email が定義されていて、 $email と出力したい場合を考えてください。 解決方法はいくつかありますが、最も単純なのはエスケープ文字を使うことです。

## The following line defines $email in this template:
#set( $email = "foo" )
$email
\$email
\\$email
\\\$email
## このテンプレートでは、次の行で $email を定義しています。
#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.

左から「\」が「$」に結合することに注意してください。 「左から結合する」規則の結果、 \\\$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.

Velocity は、定義されていない場合と定義されていない場合とで、 リファレンスの扱いが異なることに注意してください。 以下の例では、set 指示子で $foo に値 gibbous をセットします。

#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 は未定義なのでリテラルとして出力され、 $foo のところには gibbous が出力されるのです。

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

VTL 指示子をエスケープすることも可能です; この詳細については、 指示子 セクションで説明します。


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:

リファレンスに慣れると、テンプレートで効果的にリファレンスを使えるようになります。 Velocity リファレンスでは Java の利点を生かしていますが、 テンプレートデザイナでも使うのは難しくないと思います。例を挙げましょう。

$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}
$foo

$foo.getBar()
## 上と下は同じです
$foo.Bar

$data.getUser("jon")
## 上と下は同じです
$data.User("jon")

$data.getRequest().getServerName()
## 上と下は同じです
$data.Request.ServerName
## また、これも同じです
${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.

これらは、同じリファレンスのいろんな使い方の具体例です。 Velocity は、Java のイントロスペクション機能と Bean 機能を利用して、 コンテキスト内のオブジェクトと、オブジェクトメソッドの両方のリファレンス名を解決します。 テンプレート中のほぼどこにでもリファレンスを埋め込んで、評価することが可能です。

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().

Velocity では、サンマイクロシステムズが策定した Bean 仕様書に元にモデルを作ったので、 大文字と小文字を区別します。しかし、Velocity の開発者は、 ユーザエラーを出来る限り検出して訂正するよう努力しました。 getFoo() メソッドが、テンプレート内で$bar.foo によって 参照されるとき、Velocityはまず $getfoo を試み、それに失敗すると、 $getFoo を試みます。 同じように、テンプレートが $bar.Foo を参照するとき、 Velocity は最初に $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).

注意: テンプレート中のインスタンス変数への参照は解決されません。 JavaBean の getter/setter メソッドに対応する属性だけが解決されます。 (つまり、$foo.Name は、 Foo クラスのインスタンスメソッドである getName() としては解決されますが、 Foo のパブリックのインスタンス変数である Name としては解決されません。)


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.

リファレンスを使うと、 テンプレートのデザイナが Web サイト向けに動的に内容を生成できるのに対して、 指示子 (使いやすいスクリプト要素で、Java コードの出力を思い通りに操作するのに使えます) を使うと、 Web デザイナは真の意味で Web サイトの内容と見栄えを管理できるようになります。

#set #set

The #set directive is used for setting the value of a reference. 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:

左辺(LHS:Left Hand Side)は、変数リファレンスまたはプロパティリファレンスでなければなりません。 右辺(RHS:Right Hand Side)は、以下のタイプのいずれかです:

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

  • 変数リファレンス
  • 文字列リテラル
  • プロパティリファレンス
  • メソッドリファレンス
  • 数値リテラル
  • 配列リスト (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
#set( $monkey = $bill )                        ## 変数リファレンス
#set( $monkey.Friend = "monica" )              ## 文字列リテラル
#set( $monkey.Blame = $whitehouse.Leak )       ## プロパティリファレンス
#set( $monkey.Plan = $spindoctor.weave($web) ) ## メソッドリファレンス
#set( $monkey.Number = 123 )                   ## 数値リテラル
#set( $monkey.Say = ["Not", $my, "fault"] )    ## 配列リスト

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).

注意: 最後の例で [..] オペレータで定義された要素は ArrayList クラスで定義されているメソッドを使用してアクセスできます。したがって、 例えば、$monkey.Say.get(0) を使って上記の最初の要素 ("Not") にアクセスできます。

The RHS can also be a simple arithmetic expression:

右辺には単純な計算式を入れることもできます。

#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:

右辺がnullとして評価されるプロパティやメソッドだった場合、 null値は左辺に代入されません。 null代入で既存のリファレンスをコンテキストから削除することはできません。 これはVelocity初心者には混乱の元となるかもしれません。 例えば、

#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
#set( $result = $query.criteria("name") )
最初のクエリの結果は $result です。

#set( $result = $query.criteria("address") )
2番目のクエリの結果は $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" という文字列を返し、 $query.criteria("address")null を返す時、 上のVTLは次のように処理されます:

The result of the first query is bill

The result of the second query is bill
最初のクエリの結果は bill です。

2番目のクエリの結果は 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:

このため、初心者が#foreach を使って、 プロパティやメソッドリファレンスを別のリファレンスに #set し、 直後にそのリファレンスを#if 指示子でテストする、 というループを構築すると混乱しやすいでしょう。 例えば、