Template reuse

1. Core Purpose

The Velocity template engine achieves template reuse via #include / #parse.
Common webpage sections such as page header navigation _head.htm and footer copyright _footer.htm can be extracted into separate sub‑templates and imported in pages, avoiding duplicate HTML code across multiple places.

2. Key Differences Between the Two

1. #include("file path")

Outputs the raw file content as‑is; Velocity variables ($!{xxx}) inside the sub‑template will NOT be parsed

  • $!{testinclude} in sub‑templates will not be rendered; the literal string $!{testinclude} gets printed directly
  • Supports importing multiple files at once: #include("a.htm","b.htm")
  • Best for: static‑only HTML and static snippets without any VTL variables

2. #parse("file path")

Imports the sub‑template and fully interprets Velocity syntax. Variables passed from the parent template render normally inside sub‑templates

  • $!{testinclude} inside sub‑templates reads context variables and resolves to values supplied by backend code
  • Accepts only one single file path; multiple simultaneous imports are not supported
  • Best for: common templates with variables such as headers and footers (page titles, dynamic copyright text, etc.)

From your screenshot notes:
#include simply pastes sub‑template source code into the main template without parsing, while #parse performs full syntax parsing

3. Practical Example

1. Backend code (.cs)

context.Put("testinclude", "Text from sub‑template:");Code language: JavaScript (javascript)

2. Content of sub‑template _footer.htm

Copyright info $!{testinclude}
Case ① Using #include("./themes/default/_footer.htm")

Page output:

Copyright info $!{testinclude}

The variable stays unparsed; the placeholder is printed literally.

Case ② Using #parse("./themes/default/_footer.htm")

Page output:

Copyright info Text from sub‑template:Code language: JavaScript (javascript)

Variables render correctly. This explains why #parse is preferred for shared header and footer templates in real‑world projects.


4. Recommended Usage Scenarios

DirectiveUse‑case
#includeStatic assets, plain text, static HTML fragments where variable rendering is unnecessary
#parseShared headers, footers, sidebars; sub‑templates containing $variables, #if and other VTL syntax

💡 Development guidelines:
Use #parse consistently for shared components likely requiring dynamic variables, such as navigation bars and footer copyright blocks. Use #include for plain static text and style fragments.

Template reuse

Leave a Reply

Your email address will not be published. Required fields are marked *