UNPKG

13.5 kBMarkdownView Raw
1[![npm][npm]][npm-url]
2[![node][node]][node-url]
3[![deps][deps]][deps-url]
4[![tests][tests]][tests-url]
5[![coverage][cover]][cover-url]
6[![code style][style]][style-url]
7[![chat][chat]][chat-url]
8
9<div align="center">
10 <img width="110" height="100" title="PostHTML Plugin" vspace="50" src="http://michael-ciniawsky.github.io/postcss-load-plugins/logo.svg">
11 <img width="220" height="200" title="PostHTML" src="http://posthtml.github.io/posthtml/logo.svg">
12 <h1>Expressions Plugin</h1>
13</div>
14
15<h2 align="center">Install</h2>
16
17```bash
18npm i -D posthtml-expressions
19```
20
21<h2 align="center">Usage</h2>
22
23```js
24const { readFileSync } = require('fs')
25
26const posthtml = require('posthtml')
27const expressions = require('posthtml-expressions')
28
29posthtml(expressions({ locals: { foo: 'bar' } }))
30 .process(readFileSync('index.html', 'utf8'))
31 .then((result) => console.log(result.html))
32```
33
34This plugin provides a syntax for including local variables and expressions in your templates, and also extends custom tags to act as helpers for conditionals and looping.
35
36You have full control over the delimiters used for injecting locals, as well as the tag names for the conditional and loop helpers, if you need them. All options that can be passed to the `expressions` plugin are shown below:
37
38<h2 align="center">Options</h2>
39
40|Option|Default|Description|
41|:----:|:-----:|:----------|
42| **delimiters** | `['{{', '}}']` | Array containing beginning and ending delimiters for escaped locals |
43| **unescapeDelimiters** | `['{{{', '}}}']` | Array containing beginning and ending delimiters for unescaped locals |
44| **locals** | `{}` | Object containing any local variables you want to be available inside your expressions |
45| **conditionalTags** | `['if', 'elseif', 'else']` | Array containing names for tags used for `if/else if/else` statements |
46| **switchTags** | `['switch', 'case', 'default']` | Array containing names for tags used for `switch/case/default` statements |
47| **loopTags** | `['each']` | Array containing names for `for` loops |
48| **scopeTags** | `['scope']` | Array containing names for scopes |
49| **ignoredTag** | `'raw'` | String containing name of tag inside which parsing is disabled |
50| **strictMode** | `true` | Boolean value set to `false` will not throw an exception |
51
52### Locals
53
54You can inject locals into any piece of content in your html templates, other than overwriting tag names. For example, if you passed the following config to the expressions plugin:
55
56```js
57locals: { className: 'intro', name: 'Marlo', 'status': 'checked' }
58```
59
60```html
61<div class="{{ className }}">
62 <input type="radio" {{ status }}>
63 My name is {{ name }}
64</div>
65```
66
67```html
68<div class="intro">
69 <input type="radio" checked="">
70 My name is Marlo
71</div>
72```
73
74### Unescaped Locals
75
76By default, special characters will be escaped so that they show up as text, rather than html code. For example, if you had a local containing valid html as such:
77
78```js
79locals: { statement: '<strong>wow!</strong>' }
80```
81
82```html
83<p>The fox said, {{ statement }}</p>
84```
85
86```html
87<p>The fox said, &lt;strong&gt;wow!&lt;strong&gt;</p>
88```
89
90In your browser, you would see the angle brackets, and it would appear as intended. However, if you wanted it instead to be parsed as html, you would need to use the `unescapeDelimiters`, which by default are three curly brackets, like this:
91
92```html
93<p>The fox said, {{{ strongStatement }}}</p>
94```
95
96In this case, your code would render as html:
97
98```html
99<p>The fox said, <strong>wow!<strong></p>
100```
101
102### Expressions
103
104You are not limited to just directly rendering local variables either, you can include any type of javascript expressions and it will be evaluated, with the result rendered. For example:
105
106```html
107<p class="{{ env === 'production' ? 'active' : 'hidden' }}">in production!</p>
108```
109
110With this in mind, it is strongly recommended to limit the number and complexity of expressions that are run directly in your template. You can always move the logic back to your config file and provide a function to the locals object for a smoother and easier result. For example:
111
112```js
113locals: {
114 isProduction: (env) => env === 'production' ? 'active' : 'hidden'
115}
116```
117
118```html
119<p class="{{ isProduction(env) }}">in production!</p>
120```
121
122#### Ignoring Expressions
123
124Many JavaScript frameworks use `{{` and `}}` as expression delimiters. It can even happen that another framework uses the same _custom_ delimiters you have defined in this plugin.
125
126You can tell the plugin to completely ignore an expression by prepending `@` to the delimiters:
127
128```html
129<p>The @{{ foo }} is strong with this one.</p>
130```
131
132Result:
133
134```html
135<p>The {{ foo }} is strong with this one.</p>
136```
137
138### Conditionals
139
140Conditional logic uses normal html tags, and modifies/replaces them with the results of the logic. If there is any chance of a conflict with other custom tag names, you are welcome to change the tag names this plugin looks for in the options. For example, given the following config:
141
142```js
143locals: { foo: 'foo' }
144```
145
146```html
147<if condition="foo === 'bar'">
148 <p>Foo really is bar! Revolutionary!</p>
149</if>
150
151<elseif condition="foo === 'wow'">
152 <p>Foo is wow, oh man.</p>
153</elseif>
154
155<else>
156 <p>Foo is probably just foo in the end.</p>
157</else>
158```
159
160```html
161<p>Foo is probably just foo in the end.</p>
162```
163
164Anything in the `condition` attribute is evaluated directly as an expressions.
165
166It should be noted that this is slightly cleaner-looking if you are using the [SugarML parser](https://github.com/posthtml/sugarml). But then again so is every other part of html.
167
168```sml
169if(condition="foo === 'bar'")
170 p Foo really is bar! Revolutionary!
171
172elseif(condition="foo === 'wow'")
173 p Foo is wow, oh man.
174
175else
176 p Foo is probably just foo in the end.
177```
178
179#### `conditionalTags`
180
181Type: `array`\
182Default: `['if', 'elseif', 'else']`
183
184You can define custom tag names to use for creating a conditional.
185
186Example:
187
188```js
189conditionalTags: ['when', 'elsewhen', 'otherwise']
190```
191
192```html
193<when condition="foo === 'bar'">
194 <p>Foo really is bar! Revolutionary!</p>
195</when>
196
197<elsewhen condition="foo === 'wow'">
198 <p>Foo is wow, oh man.</p>
199</elsewhen>
200
201<otherwise>
202 <p>Foo is probably just foo in the end.</p>
203</otherwise>
204```
205
206Note: tag names must be in the exact order as the default ones.
207
208### Switch statement
209
210Switch statements act like streamline conditionals. They are useful for when you want to compare a single variable against a series of constants.
211
212```js
213locals: { foo: 'foo' }
214```
215
216```html
217<switch expression="foo">
218 <case n="'bar'">
219 <p>Foo really is bar! Revolutionary!</p>
220 </case>
221 <case n="'wow'">
222 <p>Foo is wow, oh man.</p>
223 </case>
224 <default>
225 <p>Foo is probably just foo in the end.</p>
226 </default>
227</switch>
228```
229
230```html
231<p>Foo is probably just foo in the end.</p>
232```
233
234Anything in the `expression` attribute is evaluated directly as an expressions.
235
236#### `switchTags`
237
238Type: `array`\
239Default: `['switch', 'case', 'default']`
240
241You can define custom tag names to use when creating a switch.
242
243Example:
244
245```js
246switchTags: ['clause', 'when', 'fallback']
247```
248
249```html
250<clause expression="foo">
251 <when n="'bar'">
252 <p>Foo really is bar! Revolutionary!</p>
253 </when>
254 <when n="'wow'">
255 <p>Foo is wow, oh man.</p>
256 </when>
257 <fallback>
258 <p>Foo is probably just foo in the end.</p>
259 </fallback>
260</clause>
261```
262
263Note: tag names must be in the exact order as the default ones.
264
265### Loops
266
267You can use the `each` tag to build loops. It works with both arrays and objects. For example:
268
269```js
270locals: {
271 array: ['foo', 'bar'],
272 object: { foo: 'bar' }
273}
274```
275
276**Array**
277```html
278<each loop="item, index in array">
279 <p>{{ index }}: {{ item }}</p>
280</each>
281```
282
283```html
284<p>1: foo</p>
285<p>2: bar</p>
286```
287
288**Object**
289```html
290<each loop="value, key in anObject">
291 <p>{{ key }}: {{ value }}</p>
292</each>
293```
294
295```html
296<p>foo: bar</p>
297```
298
299The value of the `loop` attribute is not a pure expressions evaluation, and it does have a tiny and simple custom parser. Essentially, it starts with one or more variable declarations, comma-separated, followed by the word `in`, followed by an expressions.
300
301
302```html
303<each loop="item in [1,2,3]">
304 <p>{{ item }}</p>
305</each>
306```
307
308So you don't need to declare all the available variables (in this case, the index is skipped), and the expressions after `in` doesn't need to be a local variable, it can be any expressions.
309
310#### `loopTags`
311
312Type: `array`\
313Default: `['each']`
314
315You can define custom tag names to use for creating loops:
316
317Example:
318
319```js
320loopTags: ['each', 'for']
321```
322
323You can now also use the `<for>` tag when writing a loop:
324
325```html
326<for loop="item in [1,2,3]">
327 <p>{{ item }}</p>
328</for>
329```
330
331#### Loop meta
332
333Inside a loop, you have access to a special `loop` object, which contains information about the loop currently being executed:
334
335- `loop.index` - the current iteration of the loop (0 indexed)
336- `loop.remaining` - number of iterations until the end (0 indexed)
337- `loop.first` - boolean indicating if it's the first iteration
338- `loop.last` - boolean indicating if it's the last iteration
339- `loop.length` - total number of items
340
341Example:
342
343```html
344<each loop='item in [1,2,3]'>
345 <li>Item value: {{ item }}</li>
346 <li>Current iteration of the loop: {{ loop.index }}</li>
347 <li>Number of iterations until the end: {{ loop.remaining }} </li>
348 <li>This {{ loop.first ? 'is' : 'is not' }} the first iteration</li>
349 <li>This {{ loop.last ? 'is' : 'is not' }} the last iteration</li>
350 <li>Total number of items: {{ loop.length }}</li>
351</each>
352```
353
354### Scopes
355
356You can replace locals inside certain area wrapped in a `<scope>` tag. For example you can use it after [posthtml-include](https://github.com/posthtml/posthtml-include)
357
358```js
359locals: {
360 author: { name: 'John'},
361 editor: { name: 'Jeff'}
362}
363```
364
365```html
366<scope with="author">
367 <include src="components/profile.html"></include>
368</scope>
369<scope with="editor">
370 <include src="components/profile.html"></include>
371</scope>
372```
373
374```html
375<div class="profile">
376 <div class="profile__name">{{ name }}</div>
377 <img class="profile__avatar" src="{{ image }}" alt="{{ name }}'s avatar" />
378 <a class="profile__link" href="{{ link }}">more info</a>
379</div>
380```
381
382#### `scopeTags`
383
384Type: `array`\
385Default: `['scope']`
386
387You can define a custom tag name to use for creating scopes:
388
389Example:
390
391```js
392scopeTags: ['context']
393```
394
395You can now also use the `<context>` tag when writing a scope:
396
397```html
398<context with="author">
399 <include src="components/profile.html"></include>
400</context>
401```
402
403### Ignored tag
404
405Anything inside this tag will not be parsed, allowing you to output delimiters and anything the plugin would normally parse, in their original form.
406
407```html
408<raw>
409 <if condition="foo === 'bar'">
410 <p>Output {{ foo }} as-is</p>
411 </if>
412</raw>
413```
414
415```html
416<if condition="foo === 'bar'">
417 <p>Output {{ foo }} as-is</p>
418</if>
419```
420
421You can customize the name of the tag:
422
423```js
424var opts = {
425 ignoredTag: 'verbatim',
426 locals: { foo: 'bar' } }
427}
428
429posthtml(expressions(opts))
430 .process(readFileSync('index.html', 'utf8'))
431 .then((result) => console.log(result.html))
432```
433
434```html
435<verbatim>
436 <if condition="foo === 'bar'">
437 <p>Output {{ foo }} as-is</p>
438 </if>
439</verbatim>
440```
441
442```html
443<if condition="foo === 'bar'">
444 <p>Output {{ foo }} as-is</p>
445</if>
446```
447
448<h2 align="center">Maintainers</h2>
449
450<table>
451 <tbody>
452 <tr>
453 <td align="center">
454 <img width="150 height="150"
455 src="https://avatars.githubusercontent.com/u/556932?v=3&s=150">
456 <br>
457 <a href="https://github.com/jescalan">Jeff Escalante</a>
458 </td>
459 <td align="center">
460 <img width="150 height="150"
461 src="https://avatars.githubusercontent.com/u/7034281?v=3&s=150">
462 <br>
463 <a href="https://github.com/mrmlnc">Denis Malinochkin</a>
464 </td>
465 </tr>
466 <tbody>
467</table>
468
469<h2 align="center">Contributors</h2>
470
471<table>
472 <tbody>
473 <tr>
474 <td align="center">
475 <img width="150 height="150"
476 src="https://avatars.githubusercontent.com/u/5419992?v=3&s=150">
477 <br>
478 <a href="https://github.com/michael-ciniawsky">Michael Ciniawsky</a>
479 </td>
480 <td align="center">
481 <img width="150 height="150"
482 src="https://avatars.githubusercontent.com/u/17473315?v=3&s=150">
483 <br>
484 <a href="https://github.com/xakdog">Krillin</a>
485 </td>
486 <td align="center">
487 <img width="150 height="150"
488 src="https://avatars0.githubusercontent.com/u/1656595?s=150&v=4">
489 <br>
490 <a href="https://github.com/cossssmin">Cosmin Popovici</a>
491 </td>
492 </tr>
493 <tbody>
494</table>
495
496
497[npm]: https://img.shields.io/npm/v/posthtml-expressions.svg
498[npm-url]: https://npmjs.com/package/posthtml-expressions
499
500[node]: https://img.shields.io/node/v/posthtml-expressions.svg
501[node-url]: https://nodejs.org/
502
503[deps]: https://david-dm.org/posthtml/posthtml-expressions.svg
504[deps-url]: https://david-dm.org/posthtml/posthtml-expressions
505
506[tests]: http://img.shields.io/travis/posthtml/posthtml-expressions.svg
507[tests-url]: https://travis-ci.org/posthtml/posthtml-expressions
508
509[cover]: https://coveralls.io/repos/github/posthtml/posthtml-expressions/badge.svg
510[cover-url]: https://coveralls.io/github/posthtml/posthtml-expressions
511
512[style]: https://img.shields.io/badge/code%20style-standard-yellow.svg
513[style-url]: http://standardjs.com/
514
515[chat]: https://badges.gitter.im/posthtml/posthtml.svg
516[chat-url]: https://gitter.im/posthtml/posthtml?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge"