Zum Hauptinhalt springen

Variablen in Word Vorlagen

Was dieser Leitfaden umfasst

PDF4me Word Vorlagen verwenden die var Schlüsselwort Benutzerdefinierte Variablen können direkt im Dokument deklariert werden. Nach der Deklaration kann eine Variable an beliebiger Stelle im weiteren Verlauf ausgegeben, in Schleifen neu zugewiesen werden, um laufende Summen zu bilden, oder bedingt gesetzt werden, um dynamische Meldungen zu steuern – alles ohne die Datei zu verändern. JSON Datennutzlast. Dieser Leitfaden erläutert die Syntax, die Gültigkeitsbereichsregeln, die Formatierung und praktische Muster für jedes gängige Vorlagenszenario.

Kernsyntax auf einen Blick

Erklären

Definiere eine benannte Variable und weise ihr einen Anfangswert zu:

<<var [total = 0]>>
Ausgabe

Den aktuellen Wert an beliebiger Stelle nach der Deklaration ausgeben:

<<[total]:"F2">>
Neu zuweisen

Aktualisieren Sie den Variablenwert jederzeit später:

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

Erklärung und grundlegende Verwendung

Der var Das Schlüsselwort folgt dieser Struktur:

<<var [Type Name = Value]>>

Type ist optional – die Engine leitet es aus dem Wert ab. Name ist die Kennung, auf die Sie später Bezug nehmen. Value kann ein beliebiger Literalwert, ein Datenfeld oder ein Ausdruck sein.

Einfache Zeichenkettenvariable

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

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

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

Die Variablen werden einmal deklariert und überall dort wiederverwendet, wo Konsistenz wichtig ist – ändert man den Wert an einer Stelle, wird das gesamte Dokument aktualisiert.

Variablenneuzuordnung

Eine Variable kann an einer beliebigen späteren Stelle in der Vorlage neu zugewiesen werden, indem man eine andere Variable schreibt. <<var>> Ein Tag mit demselben Namen wird hinzugefügt. Der neue Wert tritt ab diesem Zeitpunkt in Kraft.

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

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

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

Ausgabe:

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

Variablen mit Berechnungen

Variablen können das Ergebnis beliebiger arithmetischer Ausdrücke speichern, einschließlich LINQ-Aggregationen über Datenquellensammlungen.

Summen und Steuerberechnung

<<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">>

Zeichenkettenverkettung

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

Customer: <<[fullName]>>

Methoden zur Stringmanipulation

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

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

Variablen in Schleifen

Variablen deklarieren vor Die <<foreach>> Markieren und neu zuweisen innen Der Schleifenkörper. Die Engine behält den Wert über die Iterationen hinweg bei, wodurch dies zum Standardmuster für laufende Summen und Zeilenzähler wird.

Laufende Summe über alle Positionen hinweg

<<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">>

Zeilenzähler

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

Total Items: <<[counter]>>

Bedingte Variablen

Verwenden Sie die C# ternärer Operator ? : einen Variablenwert basierend auf Daten aus der Nutzlast zu verzweigen.

Statusbezeichnung

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

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

gestaffelter Rabatt

<<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">>

Vollständiges Beispiel: Rechnung mit allen Mustern

Vorlage für eine vollständige RechnungCombines 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]>>

Regeln für den Variablenbereich

Erklärt, woVerfügbar
Dokumentenstamm (vor jeder Schleife)Überall im Dokument nach der Erklärung
Im Inneren eines <<foreach>> BlockInnerhalb dieser Iteration; bleibt außerhalb bestehen, wenn es vor der Schleife deklariert wurde.
Innerhalb eines verschachtelten <<foreach>>Innerhalb dieses verschachtelten Bereichs; außerhalb nur sichtbar, wenn vorher deklariert

Faustregel: Deklarieren Sie alle benötigten Variablen außerhalb einer Schleife. vor Die <<foreach>> Durch eine erneute Zuweisung innerhalb der Schleife wird dieselbe Variable für alle nachfolgenden Zugriffe aktualisiert.

Ausgabe formatieren

Anhängen .NET Formatzeichenfolgen nach dem Variablennamen im Ausgabetag:

FormatTag-BeispielWird gerendert als
2 Dezimalstellen<<[total]:"F2">>1234.56
Ganze Zahl<<[rate * 100]:"F0">>15
Währung<<[amount]:"C2">>$1,234.56
Langes Datum<<[createdDate]:"MMMM dd, yyyy">>January 15, 2026
Kurzdatum<<[dueDate]:"MM/dd/yyyy">>01/15/2026

Bewährte Verfahren

  1. Vor Gebrauch deklarieren Die Engine verarbeitet Tags von oben nach unten; eine Variable, auf die vor ihrem Namen verwiesen wird, <<var>> Das Tag verursacht einen Fehler.
  2. Verwenden Sie beschreibende CamelCase-Namen - grandTotal, taxAmount, invoiceDate sind leichter zu warten als v1, tmp, xDie
  3. Akkumulatoren auf 0 initialisieren oder "" Vor Schleifen - die Zuweisung einer nicht initialisierten Variable im Schleifenkörper kann zu Nullreferenzfehlern führen.
  4. Einmal berechnen, vielfach verwenden - Komplexe LINQ-Ausdrücke werden in einer Variablen gespeichert, anstatt den Ausdruck in jedem Ausgabetag zu wiederholen.
  5. Namenskonflikte vermeiden - Verwenden Sie keine Namen wieder, die mit Datenquellenfeldnamen in Konflikt stehen; die Engine könnte die Referenz mehrdeutig auflösen.

Häufig gestellte Fragen

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.

Verwandte Leitfäden

Hilfe erhalten