API / Apache Velocity Interview questions
What is the difference between #set($x = $y) and context.put("x", y) in Java code?
Both make $x resolvable inside the template, but they act at different layers and different times.
| Aspect | #set inside .vm | context.put() in Java |
| Where it runs | During template rendering, inside VTL | Before rendering starts, from application code |
| Typical use | Short-lived, template-local values and derived expressions | Supplying the original data model to the template |
| Visibility to Java | Not visible to Java code after rendering | Fully controlled and testable in Java |
| Scope | Can be block-scoped inside #foreach/#macro | Available for the whole render unless overwritten |
// Java: supplies the source data context.put("price", 19.99); context.put("qty", 3);
## VTL: derives a local value from it #set($total = $price * $qty)
Using #set for something that should really come from Java, like a computed business value, is exactly the pattern the "keep logic out of templates" guidance warns against.
More Related questions...