2.3 KiB
2.3 KiB
Custom JavaScript Functions Example
This example demonstrates how to use custom JavaScript functions in Masonry templates using the Otto JavaScript interpreter. You can define custom template functions directly in your manifest.yaml
files, allowing for dynamic code generation that can be customized without recompiling the CLI tool.
Overview
The custom JavaScript functions feature allows you to:
- Define JavaScript functions in your
manifest.yaml
files - Use these functions in your templates just like built-in template functions
- Perform complex string manipulations, data transformations, and logic
- Extend template functionality dynamically
How It Works
- Define Functions: Add a
functions
section to yourmanifest.yaml
file - JavaScript Code: Each function is written in JavaScript and must define a
main()
function - Template Usage: Use the custom functions in your templates like any other template function
- Otto Execution: The Otto JavaScript interpreter executes your functions at template generation time
Function Structure
Each custom function must follow this structure:
function main() {
// Your custom logic here
// Access arguments via the global 'args' array: args[0], args[1], etc.
// Or via individual variables: arg0, arg1, etc.
return "your result";
}
Example Files
blog-example.masonry
- Sample Masonry file defining a blog applicationtemplates/manifest.yaml
- Manifest with custom JavaScript functionstemplates/model.tmpl
- Template using the custom functionstemplates/controller.tmpl
- Another template demonstrating function usage
Running the Example
# From the masonry project root
./masonry.exe generate templates examples/custom-js-functions/blog-example.masonry examples/custom-js-functions/templates manifest.yaml
Custom Functions in This Example
generateSlug
Converts a title to a URL-friendly slug:
- Input: "My Blog Post Title"
- Output: "my-blog-post-title"
pluralize
Converts singular words to plural:
- Input: "post"
- Output: "posts"
generateValidation
Creates validation rules based on field type:
- Input: field type
- Output: appropriate validation code
formatComment
Generates formatted code comments:
- Input: text
- Output: properly formatted comment block