aboutsummaryrefslogtreecommitdiff
path: root/js/README.mkd
blob: 27f2bd2c8c3a7d691b7e031bd5e64443b373b1c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
Luigi Template
==============

Overview
--------
Simple JavaScript string templating library inspired by [Unix
pipes][pipe].

Features:
* Filters via piping, with common filters built-in.
* Useful built-in filters.
* Template caching.
* Small: Less than 4k minified (see `luigi-template.min.js`),
* Stand-alone: No external dependencies (no jQuery, etc),
* Compatible: Works in browsers as old as IE9
* MIT-licensed

Installation
------------
Minify `luigi-template.js` using your minifier of choice, and drop it
into your source tree.  I like [jsmin][], personally:

    jsmin luigi-template.js > luigi-template.min.js

*Note:* If you are upgrading from a pre-0.5.0 version of Luigi Template,
be sure to include `luigi-compat.js` as well.  See the *Changes in
0.5.0* section below for details.

Usage
-----
A minimal template:

    // create template
    var t = new Luigi.Template('hello %{name}');

    // run template, print result to console
    console.log(t.run({
      name: 'Paul',
    }));

    // prints "hello Paul"

If you have a template that you only need to run one time, you can use
the `Luigi.run()` singleton to run it, like this:

    // create and run template in one shot
    var r = Luigi.run('hello %{name}', {
      name: 'Paul',
    });

    // print result to console
    console.log(r);

    // prints "hello Paul"

Templates parameters can be modified by filters.  Filters are applied to
a parameter value by appending a `|` (pipe) character, followed by the
filter name.

Here is the template from above, with the name value HTML-escaped using
a built-in filter:

    // create template that prints hello and the HTML-escaped name
    var t = new Luigi.Template('hello %{name | h}');

    // run template, print result to console
    console.log(t.run({
      name: '<Paul>',
    }));

    // prints "hello &lt;Paul&gt;"

The built-in templates are:

* `uc`: Upper-case string value.
* `lc`: Lower-case string value.
* `s`: Pluralize a value by returning `""` if the value is 1, and
  `"s"` otherwise.
* `length`: Get the length of an array.
* `trim`: Trim leading and trailing whitespace from a string.
* `h`: HTML-escape a string value.
* `u`: URL-escape a string value.
* `json`: JSON-encode a value.

You can create your own custom filters, too.

The easiest way to create your own custom filter is to add it to the set
of global filters (`Luigi.FILTERS`), like so:

    // add global template filter
    Luigi.FILTERS.barify = function(s) {
      return 'bar-' + s + '-bar';
    };

    // create template that uses custom global filter
    var t = new Luigi.Template('hello %{name | barify | h}');

    // run template, print result to console
    console.log(t.run({
      name: '<Paul>',
    }));

    // prints "hello bar-&lt;Paul&gt;-bar"

You can also create a custom filter and limit it to a particular
template by passing a custom filter hash as the second parameter to the
`Luigi.Template` constructor, like this:

    // create template with custom template-specific filter
    var t = new Luigi.Template('hello %{name | barify | h}', {
      barify: function(s) {
        return 'bar-' + s + '-bar';
      },
    });

    // run template, print result to console
    console.log(t.run({
      name: '<Paul>',
    }));

    // prints "hello bar-&lt;Paul&gt;-bar"

You can pass arguments to your custom filters.  Here's an example:

    // create template with custom template-specific filter named
    // "wrap", which wraps the value in the given filter parameters
    var t = new Luigi.Template('hello %{name | wrap head tail | h}', {
      wrap: function(s, args) {
        if (args.length == 2) {
          return [args[0], s, args[1]].join('-';
        } else if (args.length == 1) {
          return [args[0], s, args[0]].join('-');
        } else {
          return s;
        }
      },
    });

    // run template, print result to console
    console.log(t.run({
      name: '<Paul>',
    }));

    // prints "hello head-&lt;Paul&gt;-tail"

If you have a lot of separate templates, or a few large templates,
then it's a good idea to use a template cache.

A template cache will create templates as they are needed (also known as
"lazy initialization"), so the script loads quickly.  A template cache
also caches instantiated (that is, created) templates for future use, so
that running a template from the cache is fast too.

Here's how you create a template cache:

    // create template cache with a single template
    var cache = Luigi.cache({
      hello: 'hello %{name | uc | h}'
    });

    // run template, print result to console
    console.log(cache.run('hello', {
      name: '<Paul>',
    }));

    // prints "hello &lt;PAUL%gt;"

Template caches use their own set of custom filters by passing a custom
filter hash when creating a template cache:

    // create template cache with a custom filter named "reverse"
    var cache = Luigi.cache({
      hello: 'hello %{name | uc | reverse | h}'
    }, {
      reverse: function(s) {
        var cs = (s || '').split('');
        cs.reverse();
        return cs.join('');
      },
    });

    // run template, print result to console
    console.log(cache.run('hello', {
      name: '<Paul>',
    }));

    // prints "hello %gt;LUAP&lt;"

A template cache is also a convenient way to group all of the templates
in a script together:

    // add global filter named "reverse"
    Luigi.FILTERS.reverse = function(s) {
      var cs = (s || '').split('');
      cs.reverse();
      return cs.join('');
    };

    // create template cache
    var TEMPLATES = Luigi.cache({
      upper:    'hello %{name | uc | h}',
      reverse:  'hello %{name | reverse | h}',
    });

    // run the upper and reverse templates above and populate
    // the elements #upper and #reverse with their respective
    // result
    ['upper', 'reverse'].forEach(function(id) {
      getElementByid(id).innerHTML = TEMPLATES.run(id, {
        name: '<Paul>',
      });
    });

Documentation
-------------
Usage documentation is available in the *Usage* section above, and API
documentation is available online at the following URL:

https://pablotron.github.io/luigi-template/

You can also generate the documentation yourself using [jsdoc][].

Tests
-----
This `test/` directory contains the test suite for the JavaScript
implementation of [Luigi Template][], written in [Mocha][] and [Chai].

To run the test suite, load `test/test.html` in a browser.

Changes in 0.5.0
----------------
Version 0.5.0 of Luigi Template changes the namespace from
`LuigiTemplate` to `Luigi`, which has the following effects:

* old (0.4.x): `new LuigiTemplate(...)`, new (0.5): `new Luigi.Template(...)`
* old (0.4.x): `LuigiTemplate.run(...)`, new: (0.5): `Luigi.run(...)`
* old (0.4.x): `LuigiTemplate.VERSION`, new (0.5): `Luigi.VERSION`
* old (0.4.x): `LuigiTemplate.FILTERS`, new: (0.5): `Luigi.FILTERS`
* old (0.4.x): `new LuigiTemplate.Cache(...)`, new: (0.5): `Luigi.cache(...)` (recommended) or `new Luigi.Cache(...)`

If you have an existing system that you cannot make changes to, you can
include `luigi-compat.js` as a compatibility shim.  Tests for the
compatibility shim are available in `test/compat/`.

*Note:* The compatibility shim will disappear in a future release.

Author
------
Paul Duncan ([pabs@pablotron.org][me])<br/>
https://pablotron.org/

License
-------
Copyright 2014-2018 Paul Duncan ([pabs@pablotron.org][me])

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

[pipe]: https://en.wikipedia.org/wiki/Pipeline_(Unix)
[jsmin]: https://www.crockford.com/javascript/jsmin.html
[Luigi Template]: https://github.com/pablotron/luigi-template
[me]: mailto:pabs@pablotron.org
[Mocha]: https://mochajs.org/
[Chai]: http://www.chaijs.com/
[jsdoc]: http://usejsdoc.org/