Files
masonry/examples/custom-js-functions/readme.md

69 lines
2.3 KiB
Markdown

# 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
1. **Define Functions**: Add a `functions` section to your `manifest.yaml` file
2. **JavaScript Code**: Each function is written in JavaScript and must define a `main()` function
3. **Template Usage**: Use the custom functions in your templates like any other template function
4. **Otto Execution**: The Otto JavaScript interpreter executes your functions at template generation time
## Function Structure
Each custom function must follow this structure:
```javascript
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 application
- `templates/manifest.yaml` - Manifest with custom JavaScript functions
- `templates/model.tmpl` - Template using the custom functions
- `templates/controller.tmpl` - Another template demonstrating function usage
## Running the Example
```bash
# 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