markdown
2025-11-13
concepts
Description
aaaaaaaaa
Code
# Template Engine TourThis is a comprehensive guide to the Snippy template engine syntax. The template engine provides powerful text generation capabilities with variable substitution, conditionals, loops, expressions, and more.## Quick StartSnippy templates are plain text files with special syntax for dynamic content. The engine processes templates and produces final output by evaluating expressions and statements.### Basic Syntax OverviewThe template engine uses three types of delimiters:- `` - **Expressions**: Output values, variables, and calculations- `` - **Statements**: Control flow, variable assignment, and commands- `` - **Comments**: Documentation that doesn't appear in output## 1. Plain Text and CommentsTemplates can contain regular text that passes through unchanged:```Hello World!This is plain text.```Comments are ignored during processing:```Text before commentText after comment```**Output:**```Text before commentText after comment```## 2. Variables and Expressions### Variable OutputUse double braces to output variable values:```Hello !Welcome to .```With variables `name="Alice"` and `place="Wonderland"`:```Hello Alice!Welcome to Wonderland.```### Setting VariablesUse the `` statement to define variables:``` !```**Output:**```Hello John!```### Dot Notation for Namespaced VariablesVariables can have hierarchical names using dots:```Database: :```**Output:**```Database: localhost:5432```### Clearing VariablesUse the `` statement to remove variables from memory:```Before clear: Items: , After clear: Items: , ```**Output:**```Before clear: Hello WorldItems: apple, bananaAfter clear:Items: ,```The clear statement can:- Clear individual variables: ``- Clear entire namespaces: `` removes all variables starting with `namespace.`- Safely handle non-existent variables (no error if the variable doesn't exist)### Capture StatementThe `` statement allows you to capture template output within a specific scope and store it in a variable. This is useful for generating complex content that you want to reuse or process further.```Hello ! You have new messages.Generated message: Final output: ```**Output:**```Generated message: Hello Alice! You have 3 new messages.That's quite a few!Final output: Message: Hello Alice! You have 3 new messages.That's quite a few!```The capture statement:- Captures all output (text, variables, expressions) within its scope- Stores the captured content in the specified variable- Can contain complex logic including conditionals, loops, and nested expressions- Preserves formatting and newlines from the captured content- Can be nested within other statements for advanced template composition## 3. Arithmetic and Expressions### Basic ArithmeticThe template engine supports standard mathematical operations with both integers and floating-point numbers:```Result: 8Product: 28Division: 5.0Subtraction: 8```**Output:**```Result: 8Product: 28Division: 5Subtraction: 8```### Float ArithmeticFloating-point numbers are fully supported in calculations:```Float result: 7.8Mixed: 13.14Division: 3.142857142857143Precision: 3.0```**Output:**```Float result: 7.8Mixed: 13.14Division: 3.14286Precision: 3.0```### Order of Operations and ParenthesesMathematical precedence is respected, and parentheses can override it:```Order of operations: 14With parentheses: 20Complex: 13Mixed operations: 17.0```**Output:**```Order of operations: 14With parentheses: 20Complex: 13Mixed operations: 17```### Type CastingConvert between numeric types using `int()`:```Float value: Integer value: Complex casting: ```**Output:**```Float value: 42.7Integer value: 42Complex casting: 255```## 4. String Operations### String ConcatenationUse the `~` operator for string concatenation (different from arithmetic `+`):``` Literal concatenation```**Output:**```Hello WorldLiteral concatenation```**String Concatenation vs Addition:**```Concatenation: Addition: ```**Output:**```Concatenation: HelloWorldAddition: HelloWorld```Both `~` and `+` work for string concatenation, but `~` is explicitly for strings while `+` also handles arithmetic. Use `~` when you want to be explicit about string concatenation.**Complex Concatenation:**``` Result: 8 items```### String LiteralsStrings can be defined with double quotes:```This is a string literalStrings can contain spaces and symbols!```**Output:**```This is a string literalStrings can contain spaces and symbols!```## 5. Null CoalescingUse `??` to provide fallback values for undefined variables:```Default: Found: ```With variable `name="Alice"` (and `missing` undefined):```Default: fallback valueFound: Alice```Complex null coalescing with expressions:```Complex: ```## 6. Ternary OperatorUse the ternary operator `condition ? true_value : false_value` for conditional expressions:```Status check: Greeting: Priority level: ```**Output:**```Status check: enabledGreeting: Hello WorldPriority level: normal```### Ternary with FiltersCombine ternary operators with filters for powerful conditional transformations:```With filters on true branch: With filters on false branch: With filters on both branches: ```**Output:**```With filters on true branch: WORLDWith filters on false branch: NOT FOUNDWith filters on both branches: ACTIVE```### Nested Ternary ExpressionsTernary operators can be nested for complex conditional logic:```Nested ternary: ```**Output:**```Nested ternary: HIGH```## 7. Filters and PipesApply transformations to values using the pipe operator `|`:```Uppercase: Lowercase: Chain filters: MIXED CASE```**Output:**```Uppercase: HELLO WORLDLowercase: hello worldChain filters: MIXED CASE```Available filters:- `upper` - Convert to uppercase- `lower` - Convert to lowercase- `escape` - Convert special characters to escaped quoted string- `quote` - Wrap in quotes and escape internal quotes/backslashes- `join` - Join list elements with a separator### Escape FilterThe `escape` filter converts strings with special characters into quoted strings with proper escape sequences:```Escaped newline: Escaped tab: Escaped quotes: ```**Output:**```Escaped newline: "Line 1\nLine 2"Escaped tab: "before\tafter"Escaped quotes: "She said \"hello\""```The escape filter handles:- `\n` - Newline characters- `\t` - Tab characters- `\r` - Carriage return characters- `\"` - Double quote characters- `\\` - Backslash characters- `\0` - Null charactersThe output is always wrapped in double quotes, making it suitable for generating code or configuration files.### Quote FilterThe `quote` filter wraps strings in double quotes and escapes internal quotes and backslashes:```Simple: With quote: With backslash: Literal: ```**Output:**```Simple: "test"With quote: "test\"test"With backslash: "test\\test"Literal: "hello"```### Join FilterThe `join` filter combines list elements into a single string with a specified separator:```Combined: Comma separated: No separator: ```**Output:**```Combined: KEY_A | KEY_B | KEY_XComma separated: KEY_A, KEY_B, KEY_XNo separator: KEY_AKEY_BKEY_X```**Filter Chaining:**Filters can be chained and work with string literals, variables, or complex expressions:```Basic variable: Chained filters: MIXEDExpression with filter: worldMultiple chains: TEST```**Output:**```Basic variable: JOHNChained filters: MIXEDExpression with filter: hello worldMultiple chains: TEST```## 8. Conditional Logic### Basic ConditionalsUse `` statements for conditional content:``````With variable `enabled="true"` (and `disabled` undefined):```Feature is enabled!```### If-Elif-Else ChainsComplex conditional logic with multiple branches:```` and `` can close conditional blocks:```Content here```## 9. Loops### Basic LoopsRepeat content a specific number of times:```Hello World!```**Output:**```Hello World!Hello World!Hello World!```### Variable-Driven LoopsUse variables to control loop count:```Iteration```### Foreach LoopsIterate over namespaced variables:```Key: , Value: ```**Output:**```Key: one, Value: firstKey: two, Value: secondKey: three, Value: third```In `` loops:- `` contains the variable suffix (after the dot)- `` contains the variable's value### Nested ForeachHandle multiple namespaced variable sets:```Users:: Products:: $```## 10. Lists### Basic List CreationCreate ordered lists using square bracket syntax:```First fruit: Second fruit: Third fruit: ```**Output:**```First fruit: appleSecond fruit: bananaThird fruit: cherry```Lists are zero-indexed, so the first element is accessed with `.0`, second with `.1`, etc.### Mixed Data Types in ListsLists can contain different types of values including variables, numbers, and strings:```Index 0: Index 1: Index 2: Index 3: ```With variable `var0="default_value"`:```Index 0: default_valueIndex 1: 1Index 2: 2Index 3: string```### Lists with ExpressionsList elements can be complex expressions:```First number: Calculated result: ```**Output:**```First number: 1Calculated result: 8```### Iterating Over Lists with ForeachLists work seamlessly with `` loops:```Item : ```**Output:**```Item 0: firstItem 1: secondItem 2: third```In list iteration:- `` contains the numeric index (0, 1, 2, ...)- `` contains the list element value### Empty ListsEmpty lists can be created and handled gracefully:```Before foreachThis will not appearAfter foreach```**Output:**```Before foreachAfter foreach```### Comprehensive List ExampleCombining multiple list features:```Numbers:: Expressions:: Direct access: , ```**Output:**```Numbers:0: 11: 22: 33: 44: 5Expressions:0: 31: 82: 5Direct access: 1, 8```## 11. Dictionaries and ObjectsCreate key-value structures using dictionary syntax:```Server: :Application: ```**Output:**```Server: localhost:8080Application: MyApp```Dictionary values can be strings, numbers, or variables:```Environment: Debug: Max users: ```## 12. List Operations### Append List StatementAdd items to existing lists using ``:``````With variables `arg.a=true`, `arg.b=false`, `arg.x=true`:```Keys found: KEY_A, KEY_X```The `append_list` statement dynamically adds elements to lists, making it useful for conditional list building.### Append Unique Sub StatementAdd content to a variable only if it doesn't already exist using ``:```List: ```**Output:**```List: item1item2item3```The `append_unique_sub` statement checks if the content already exists in the variable before appending it, preventing duplicates. This is useful for building strings where repeated content should be avoided.### List with Join Filter in PracticeCombining list operations with filters for real-world use cases:``````## 13. Unique Line ProcessingRemove duplicate lines from content blocks:```line1line2line1line3line2```**Output:**```line1line2line3```This is useful for generating lists where duplicates should be eliminated.## 14. AttachmentsLoad external content into variables using the attachment system:```Before attachmentAfter attachment```The attachment identifier (`"test_attachment"`) is resolved by the application's attachment resolver, which loads the content into the specified variable (`content`).## 15. MacrosThe macro system allows you to define reusable template fragments with parameters. Macros help reduce duplication and create modular, maintainable templates.### Basic Macro DefinitionDefine a macro using ``:``````**Output:**```banner motd ^===========================================| This device is property of BigCorpCo || Unauthorized access is unauthorized || Unless you're authorized to access it || In which case play nice and stay safe |===========================================^```### Macros with ParametersMacros can accept parameters to make them more flexible:``````**Output:**```Unused port, dedicated to Home Computer devicesUnused port, dedicated to Server devices```### Multiple ParametersMacros support multiple parameters separated by commas:``````**Output:**```User: jdoeRole: Senior DeveloperDepartment: Engineering```### Macros with LogicMacros can contain any template constructs including conditionals and expressions:``````**Output:**```🔴 HIGH: Server Down🟡 MEDIUM: Maintenance🟢 All Good```### Nested Macro CallsMacros can call other macros:``````**Output:**```ID: E001Name: John DoeDepartment: IT```### Network Configuration Example``````**Output:**```vlan 100 name USERS!interface vlan100 ip address 192.168.100.1 255.255.255.0 no shutdownvlan 200 name SERVERS!interface vlan200 ip address 192.168.200.1 255.255.255.0 no shutdown```### Whitespace ControlUse `` to control whitespace in macro output:```Items: ```**Output:**```Items: apple, banana, cherry```### Macro Best Practices1. **Use descriptive names**: `create_user_card()` instead of `card()`2. **Keep macros focused**: One responsibility per macro3. **Document parameters**: Use clear parameter names4. **Handle edge cases**: Check for empty or missing parameters5. **Use whitespace control**: Manage output formatting with ``## 16. Advanced Expression Examples### Complex ExpressionsCombine multiple features in sophisticated expressions:```Basic parentheses: 20Nested parentheses: 13Multiple parentheses levels: 50Complex null coalescing: Type casting: Mixed operators with casting: Deeply nested: Division with parentheses: Null coalescing with zero: ```**Output (with sample variables):**```Basic parentheses: 20Nested parentheses: 13Multiple parentheses levels: 50Complex null coalescing: 25.0Type casting: 255Mixed operators with casting: 314Deeply nested: 12Division with parentheses: 25Null coalescing with zero: 52```### String and Arithmetic MixingCombine string concatenation with arithmetic:```String concat: Mixed operations: ```## 17. Error Handling and Edge Cases### Empty TemplatesEmpty templates produce empty output:```(empty file)```**Output:**```(empty output)```### Undefined VariablesUndefined variables in expressions evaluate to empty strings or zero in arithmetic contexts:```Undefined in text: Undefined in arithmetic: With null coalescing: ```**Output:**```Undefined in text:Undefined in arithmetic: 5With null coalescing: default```### Conditional Edge CasesVariables are considered false if:- They are undefined- They are empty strings- They contain only whitespace```Non-empty string is true```## 18. Best Practices### Variable Naming- Use descriptive names: `config.database.host` instead of `h`- Use dots for hierarchical organization: `user.profile.name`- Keep names readable: `max_items` instead of `mi`### Template Organization- Use comments to document complex logic- Break complex expressions into multiple variables- Group related variable assignments### Performance Considerations- Minimize deep nesting in expressions- Use null coalescing for optional variables- Prefer simple conditionals over complex boolean logic- Use ternary operators for simple conditional values### Example: Well-Structured Template```# Server ConfigurationHost: Port: ```
Comments
No comments yet. Be the first to comment!
Please login to leave a comment.