0.1.4 • Published 5 months ago
@mdfriday/text-template v0.1.4
@mdfriday/text-template
A lightweight, efficient text templating engine implemented in TypeScript for modern JavaScript and TypeScript applications.
This package is a TypeScript implementation of the Go template package, providing powerful text templating capabilities with a familiar syntax.
Installation
npm install @mdfriday/text-template
Features
- Go-like template syntax
- Powerful control structures (if, range, with, template)
- Variable interpolation
- Function calls
- Nested templates
- Whitespace control
- Custom delimiters
Basic Usage
import { New } from '@mdfriday/text-template';
// Create a new template
const tmpl = New('example');
// Parse a template string
const [parsedTmpl, parseErr] = tmpl.Parse('Hello, {{.Name}}!');
if (parseErr) {
console.error('Parse error:', parseErr);
return;
}
// Execute the template with data
const [result, execErr] = parsedTmpl.Execute({ Name: 'World' });
if (execErr) {
console.error('Execution error:', execErr);
return;
}
console.log(result); // Output: Hello, World!
Template Syntax
Variables
{{ .Name }} // Access a field
{{ .User.Name }} // Access a nested field
{{ $variable }} // Access a variable
Control Structures
If-Else
{{ if .Condition }}
Condition is true
{{ else }}
Condition is false
{{ end }}
Range
{{ range .Items }}
{{ . }} // The dot represents the current item
{{ end }}
{{ range $index, $item := .Items }}
{{ $index }}: {{ $item }}
{{ end }}
With
{{ with .User }}
Name: {{ .Name }}
Email: {{ .Email }}
{{ end }}
Functions
{{ len .Items }}
{{ index .Items 0 }}
{{ printf "%.2f" .Value }}
Real-World Example: YouTube Shortcode
Here's an example of how to use this template engine to create a YouTube embed shortcode:
import { New } from '@mdfriday/text-template';
// Define the YouTube shortcode template
const youtubeTemplate = `
{{- $ytHost := "www.youtube.com" -}}
{{- $id := .Get "id" | default (.Get 0) -}}
{{- $class := .Get "class" | default (.Get 1) -}}
{{- $title := .Get "title" | default "YouTube Video" }}
<div {{ with $class }}class="{{ . }}"{{ else }}style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;"{{ end }}>
<iframe src="https://{{ $ytHost }}/embed/{{ $id }}{{ with .Get "autoplay" }}{{ if eq . "true" }}?autoplay=1{{ end }}{{ end }}" {{ if not $class }}style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" {{ end }}allowfullscreen title="{{ $title }}"></iframe>
</div>
`;
// Create a template
const tmpl = New('youtube');
// Add custom functions
tmpl.Funcs(new Map([
['default', (value, defaultValue) => value || defaultValue],
['eq', (a, b) => a === b],
['not', (value) => !value],
['with', (value, fn) => value ? fn(value) : '']
]));
// Parse the template
const [parsedTmpl, parseErr] = tmpl.Parse(youtubeTemplate);
if (parseErr) {
console.error('Parse error:', parseErr);
return;
}
// Example data with a Get method to simulate Hugo's shortcode parameters
const data = {
Get: (name) => {
const params = {
'0': 'dQw4w9WgXcQ', // YouTube video ID as positional parameter
'title': 'Never Gonna Give You Up'
};
return params[name];
}
};
// Execute the template
const [result, execErr] = parsedTmpl.Execute(data);
if (execErr) {
console.error('Execution error:', execErr);
return;
}
console.log(result);
This will output:
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
<iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" allowfullscreen title="Never Gonna Give You Up"></iframe>
</div>
API Reference
Template
The main template class with methods for parsing and executing templates.
import { Template, New } from '@mdfriday/text-template';
// Create a new template
const tmpl = New('example');
Methods
Parse(text: string): [Template, Error | null]
- Parse a template stringExecute(data: any): [string, Error | null]
- Execute the template with dataExecuteTemplate(name: string, data: any): [string, Error | null]
- Execute a named templateFuncs(funcMap: FuncMap): Template
- Add functions to the templateDelims(left: string, right: string): Template
- Set custom delimiters
License
UNLICENSED - This is a private package for commercial use only. Copyright (c) 2025 MDFriday.