README.md
1# pug-attrs
2
3Generate code for Pug attributes
4
5[](https://travis-ci.org/pugjs/pug-attrs)
6[](https://david-dm.org/pugjs/pug?path=packages/pug-attrs)
7[](https://www.npmjs.org/package/pug-attrs)
8
9## Installation
10
11 npm install pug-attrs
12
13## Usage
14
15```js
16var compileAttrs = require('pug-attrs');
17```
18
19### `compileAttrs(attrs, options)`
20
21Compile `attrs` to a JavaScript string that evaluates to the attributes in the desired format.
22
23`options` MUST include the following properties:
24
25- `terse`: whether or not to use HTML5-style terse boolean attributes
26- `runtime`: callback that takes a runtime function name and returns the source code that will evaluate to that function at runtime
27- `format`: output format; must be `html` or `object`
28
29`attrs` is an array of attributes, with each attribute having the form of `{ name, val, mustEscape }`. `val` represents a JavaScript string that evaluates to the value of the attribute, either statically or dynamically.
30
31```js
32var compileAttrs = require('pug-attrs');
33var pugRuntime = require('pug-runtime');
34
35function getBaz () { return 'baz<>'; }
36
37var attrs = [
38 {name: 'foo', val: '"bar"', mustEscape: true },
39 {name: 'baz', val: 'getBaz()', mustEscape: true },
40 {name: 'quux', val: true, mustEscape: false}
41];
42var result, finalResult;
43
44// HTML MODE
45result = compileAttrs(attrs, {
46 terse: true,
47 format: 'html',
48 runtime: function (name) { return 'pugRuntime.' + name; }
49});
50//=> '" foo=\\"bar\\"" + pugRuntime.attr("baz", getBaz(), true, true) + " quux"'
51
52finalResult = Function('pugRuntime, getBaz',
53 'return (' + result + ');'
54);
55finalResult(pugRuntime, getBaz);
56// => ' foo="bar" baz="baz<>" quux'
57
58// OBJECT MODE
59result = compileAttrs(attrs, {
60 terse: true,
61 format: 'object',
62 runtime: function (name) { return 'pugRuntime.' + name; }
63});
64//=> '{"foo": "bar","baz": pugRuntime.escape(getBaz()),"quux": true}'
65
66finalResult = Function('pugRuntime, getBaz',
67 'return (' + result + ');'
68);
69finalResult(pugRuntime, getBaz);
70//=> { foo: 'bar', baz: 'baz<>', quux: true }
71```
72
73## License
74
75 MIT
76