メインコンテンツへスキップ

変数 Word テンプレート

このガイドの内容

PDF4me Word テンプレートは var キーワード ドキュメント内でカスタム変数を直接宣言します。宣言された変数は、下流のどこにでも出力したり、ループ内で再割り当てして累積合計を構築したり、条件付きで設定して動的なメッセージングを駆動したりできます。これらすべては、 JSON データペイロード。このガイドでは、一般的なテンプレートシナリオごとに、構文、スコープ規則、書式設定、および実用的なパターンについて説明します。

コア構文の概要​

宣言する

名前付き変数を定義し、初期値を割り当てます。

<<var [total = 0]>>
出力

宣言後の任意の場所に現在の値を表示する:

<<[total]:"F2">>
再割り当て

変数の値は、後からいつでも更新できます。

<<var [total = total + item.price]>>

宣言と基本的な使用方法​

の var キーワードは次の構造に従います。

<<var [Type Name = Value]>>

Type これはオプションです。エンジンが値から推測します。 Name これは後で参照する識別子です。 Value 任意のリテラル、データフィールド、または式を指定できます。

単純な文字列変数​

<<var [companyName = "Acme Corp"]>>
<<var [companyPhone = "+1-555-0123"]>>

Company: <<[companyName]>>
Contact: <<[companyPhone]>>

For questions, please reach <<[companyName]>> at <<[companyPhone]>>.

変数は一度宣言すれば、一貫性が重要なあらゆる場所で再利用されます。つまり、一箇所で値を変更するだけで、ドキュメント全体が更新されます。

変数の再割り当て​

テンプレート内の後続の箇所で変数を再割り当てするには、別の変数を記述します。 <<var>> 同名のタグ。新しい値はその時点から有効になります。

<<var [status = "Pending"]>>
Current Status: <<[status]>>

<<var [status = "Approved"]>>
Updated Status: <<[status]>>

<<var [status = "Completed"]>>
Final Status: <<[status]>>

出力:

Current Status: Pending
Updated Status: Approved
Final Status: Completed

計算式を含む変数​

変数には、データソースコレクションに対するLINQ集計を含む、あらゆる算術式の結果を保持できます。

合計金額と税額計算​

<<var [subtotal = lineItems.Sum(i => i.quantity * i.price)]>>
<<var [taxRate = 0.10]>>
<<var [taxAmount = subtotal * taxRate]>>
<<var [total = subtotal + taxAmount]>>

Subtotal: $<<[subtotal]:"F2">>
Tax (10%): $<<[taxAmount]:"F2">>
Total: $<<[total]:"F2">>

文字列連結​

<<var [firstName = "Jane"]>>
<<var [lastName = "Smith"]>>
<<var [fullName = firstName + " " + lastName]>>

Customer: <<[fullName]>>

文字列操作メソッド​

<<var [upperName = customerName.ToUpper()]>>
<<var [initials = firstName.Substring(0,1) + lastName.Substring(0,1)]>>

Customer: <<[upperName]>>
Initials: <<[initials]>>

ループ内の変数​

変数を宣言する 前に の <<foreach>> タグ付けして再割り当てする 内部 ループ本体。このエンジンは値を反復処理間で引き継ぐため、累計や行数カウンターの標準的なパターンとなっています。

明細項目全体の累計​

<<var [runningTotal = 0.0]>>
<<foreach [item in lineItems]>>
<<var [lineTotal = item.quantity * item.price]>>
<<var [runningTotal = runningTotal + lineTotal]>>
<<[item.description]>> - <<[item.quantity]>> × $<<[item.price]:"F2">> = $<<[lineTotal]:"F2">> (Running: $<<[runningTotal]:"F2">>)
<</foreach>>

Final Total: $<<[runningTotal]:"F2">>

列カウンター​

<<var [counter = 0]>>
<<foreach [item in items]>>
<<var [counter = counter + 1]>>
<<[counter]>>. <<[item.name]>>
<</foreach>>

Total Items: <<[counter]>>

条件付き変数​

使用する C# 三項演算子 ? : ペイロードからのデータに基づいて変数値を分岐させる。

ステータスラベル​

<<var [statusLabel = orderStatus == "Completed" ? "✓ Complete" : "⚠ Pending"]>>
<<var [urgency = daysUntilDue < 7 ? "URGENT" : "Standard"]>>

Priority: <<[urgency]>>
Status: <<[statusLabel]>>

段階的割引​

<<var [subtotal = items.Sum(i => i.price)]>>
<<var [discountRate = subtotal > 1000 ? 0.15 : 0.05]>>
<<var [discountAmount = subtotal * discountRate]>>
<<var [total = subtotal - discountAmount]>>

Subtotal: $<<[subtotal]:"F2">>
Discount (<<[discountRate * 100]:"F0">>%):: $<<[discountAmount]:"F2">>
Total: $<<[total]:"F2">>

完全な例:すべてのパターンを含む請求書​

請求書テンプレート全文Combines declaration, running totals in a loop, conditional discount, and formatted output.
<<var [companyName = "Tech Solutions Inc."]>>
<<var [proposalDate = DateTime.Now]>>
<<var [validUntil = proposalDate.AddDays(30)]>>

Invoice Date: <<[proposalDate]:"MMMM dd, yyyy">>
Valid Until: <<[validUntil]:"MMMM dd, yyyy">>

Line Items:
<<var [subtotal = 0.0]>>
<<foreach [item in lineItems]>>
<<var [lineTotal = item.quantity * item.unitPrice]>>
<<var [subtotal = subtotal + lineTotal]>>
• <<[item.description]>> - <<[item.quantity]>> @ $<<[item.unitPrice]:"F2">> = $<<[lineTotal]:"F2">>
<</foreach>>

<<var [discountRate = subtotal > 5000 ? 0.10 : 0.05]>>
<<var [discountAmount = subtotal * discountRate]>>
<<var [afterDiscount = subtotal - discountAmount]>>
<<var [tax = afterDiscount * 0.08]>>
<<var [grandTotal = afterDiscount + tax]>>

Subtotal: $<<[subtotal]:"F2">>
Discount (<<[discountRate * 100]:"F0">>%):: $<<[discountAmount]:"F2">>
After Discount: $<<[afterDiscount]:"F2">>
Tax (8%): $<<[tax]:"F2">>
Grand Total: $<<[grandTotal]:"F2">>

Prepared by: <<[companyName]>>

可変範囲ルール​

宣言された場所利用可能
ドキュメントルート(ループ処理の前)宣言以降の文書全体
内部 <<foreach>> ブロックその反復処理内では有効ですが、ループの前に宣言されている場合はループ外でも有効です。
入れ子になった内部 <<foreach>>そのネストされたスコープ内。事前に宣言されている場合のみ外部から見える。

経験則: 必要な変数はループの外で宣言してください。 前に の <<foreach>> タグ。ループ内で再代入すると、以降のすべての参照で同じ変数が更新されます。

出力の書式設定​

追加する .NET 出力タグ内の変数名の後にフォーマット文字列を追加します。

形式タグの例レンダリング結果
小数点以下2桁<<[total]:"F2">>1234.56
整数<<[rate * 100]:"F0">>15
通貨<<[amount]:"C2">>$1,234.56
長期デート<<[createdDate]:"MMMM dd, yyyy">>January 15, 2026
短期デート<<[dueDate]:"MM/dd/yyyy">>01/15/2026

ベストプラクティス​

  1. 使用前に申告してください - エンジンはタグを上から下に処理します。その前に参照された変数は <<var>> タグがエラーを引き起こします。
  2. 説明的なキャメルケース名を使用してください - grandTotal、 taxAmount、 invoiceDate 維持管理が容易な v1、 tmp、 x。
  3. アキュムレータを0に初期化する または "" ループの前に - ループ本体内で初期化されていない変数に値を代入すると、ヌル参照エラーが発生する可能性があります。
  4. 一度計算すれば、何度でも使える 複雑なLINQ式は、出力タグごとに式を繰り返すのではなく、変数に格納してください。
  5. 名前の衝突を避ける - データソースのフィールド名と競合する名前を再利用しないでください。エンジンが参照を曖昧に解決する可能性があります。

よくある質問​

What is the var keyword in PDF4me templates?+
The var keyword declares a named variable inside a Word template using the syntax <<var [name = value]>>. Once declared, the variable can be output with <<[name]>> and reassigned at any later point. Variables can hold strings, numbers, dates, booleans, or the result of any expression supported by the Aspose.Words LINQ Reporting Engine, including LINQ aggregates over data-source collections.
Can I use variables inside foreach loops?+
Yes. Variables declared outside a foreach block are accessible inside it and can be reassigned on each iteration. This is the standard pattern for running totals: declare <<var [total = 0]>> before the loop, then add <<var [total = total + item.amount]>> inside the loop body. After the closing <</foreach>> tag, <<[total]>> holds the accumulated sum across all iterations.
Are variables available throughout the entire document?+
A variable is available from the point of its declaration to the end of the document. Variables declared at the document root level are accessible everywhere below, including inside nested loops and conditionals. Variables first declared inside a foreach block persist after the loop closes but may not be accessible before the loop's first iteration - always declare and initialize shared variables at the root level.
Can I perform math and string operations in a variable assignment?+
Yes. The expression inside <<var [name = expression]>> supports any standard C# expression: arithmetic operators (+, -, *, /), string concatenation (+), instance method calls (.ToUpper(), .Substring(), .ToString()), LINQ extension methods (.Sum(), .Count(), .Average(), .Max()), and ternary conditionals (?:). You can also reference other previously declared variables in the expression.
How do I format a numeric variable in the output?+
Append a .NET format string to the output tag: <<[total]:"F2">> renders two decimal places, <<[rate * 100]:"F0">> shows a whole-number percentage, <<[amount]:"C2">> formats as currency, and <<[date]:"MMMM dd, yyyy">> produces a long date. Any standard .NET composite format string is valid - the full list is available in the Microsoft .NET documentation for standard numeric and date format strings.

関連ガイド​

ヘルプが必要な場合​