跳到主要内容

变量 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 输出标签中变量名后的格式字符串:

格式标签示例渲染结果为
保留两位小数<<[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. 使用描述性的驼峰式命名法 - grandTotaltaxAmountinvoiceDate 比……更容易维护 v1tmpx
  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.

相关指南

获取帮助