1 | # ![common-tags](media/logo.svg)
|
2 |
|
3 | 🔖 A set of **well-tested**, commonly used template literal tag functions for use in ES2015+.
|
4 |
|
5 | 🌟 Plus some extra goodies for easily making your own tags.
|
6 |
|
7 | ## Example
|
8 |
|
9 | ```js
|
10 | import { html } from 'common-tags';
|
11 |
|
12 | html`
|
13 | <div id="user-card">
|
14 | <h2>${user.name}</h2>
|
15 | </div>
|
16 | `
|
17 | ```
|
18 |
|
19 | ## Project Status
|
20 |
|
21 | | Info | Badges |
|
22 | | ---------- | ---------------------------------------- |
|
23 | | Version | [![github release](https://img.shields.io/github/release/declandewet/common-tags.svg?style=flat-square)](https://github.com/declandewet/common-tags/releases/latest) [![npm version](https://img.shields.io/npm/v/common-tags.svg?style=flat-square)](http://npmjs.org/package/common-tags) |
|
24 | | License | [![npm license](https://img.shields.io/npm/l/common-tags.svg?style=flat-square)](https://github.com/declandewet/common-tags/blob/master/license.md) |
|
25 | | Popularity | [![npm downloads](https://img.shields.io/npm/dm/common-tags.svg?style=flat-square)](http://npm-stat.com/charts.html?package=common-tags) |
|
26 | | Testing | [![Build status](https://ci.appveyor.com/api/projects/status/75eiommx0llt3sgd?svg=true)](https://ci.appveyor.com/project/declandewet/common-tags) [![build status](https://img.shields.io/travis/declandewet/common-tags.svg?style=flat-square)](https://travis-ci.org/declandewet/common-tags) [![codecov.io](https://img.shields.io/codecov/c/gh/declandewet/common-tags.svg?style=flat-square)](https://codecov.io/gh/declandewet/common-tags?branch=master) |
|
27 | | Quality | [![bitHound Overall Score](https://www.bithound.io/github/declandewet/common-tags/badges/score.svg)](https://www.bithound.io/github/declandewet/common-tags) [![dependency status](https://img.shields.io/david/declandewet/common-tags.svg?style=flat-square)](https://david-dm.org/declandewet/common-tags) [![dev dependency status](https://img.shields.io/david/dev/declandewet/common-tags.svg?style=flat-square)](https://david-dm.org/declandewet/common-tags#info=devDependencies) |
|
28 | | Style | [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 | ## Table of Contents
|
34 |
|
35 | - [Introduction](#introduction)
|
36 | - [Why You Should Care](#why-you-should-care)
|
37 | - [See Who Is Using `common-tags`](#see-who-is-using-common-tags)
|
38 | - [Installation](#installation)
|
39 | - [Requirements](#requirements)
|
40 | - [Instructions](#instructions)
|
41 | - [Usage](#usage)
|
42 | - [Imports](#imports)
|
43 | - [Available Tags](#available-tags)
|
44 | - [`html`](#html)
|
45 | - [Aliases: `source`, `codeBlock`](#aliases-source-codeblock)
|
46 | - [`safeHtml`](#safehtml)
|
47 | - [`oneLine`](#oneline)
|
48 | - [`oneLineTrim`](#onelinetrim)
|
49 | - [`stripIndent`](#stripindent)
|
50 | - [`stripIndents`](#stripindents)
|
51 | - [`inlineLists`](#inlinelists)
|
52 | - [`oneLineInlineLists`](#onelineinlinelists)
|
53 | - [`commaLists`](#commalists)
|
54 | - [`commaListsOr`](#commalistsor)
|
55 | - [`commaListsAnd`](#commalistsand)
|
56 | - [`oneLineCommaLists`](#onelinecommalists)
|
57 | - [`oneLineCommaListsOr`](#onelinecommalistsor)
|
58 | - [`oneLineCommaListsAnd`](#onelinecommalistsand)
|
59 | - [Advanced Usage](#advanced-usage)
|
60 | - [Tail Processing](#tail-processing)
|
61 | - [Using Tags on Regular String Literals](#using-tags-on-regular-string-literals)
|
62 | - [Type Definitions](#type-definitions)
|
63 | - [Make Your Own Template Tag](#make-your-own-template-tag)
|
64 | - [Class is in Session: TemplateTag](#class-is-in-session-templatetag)
|
65 | - [The Anatomy of a Transformer](#the-anatomy-of-a-transformer)
|
66 | - [Plugin Transformers](#plugin-transformers)
|
67 | - [Plugin Pipeline](#plugin-pipeline)
|
68 | - [Returning Other Values from a Transformer](#returning-other-values-from-a-transformer)
|
69 | - [List of Built-in Transformers](#list-of-built-in-transformers)
|
70 | - [`trimResultTransformer([side])`](#trimresulttransformerside)
|
71 | - [`stripIndentTransformer([type='initial'])`](#stripindenttransformertypeinitial)
|
72 | - [`replaceResultTransformer(replaceWhat, replaceWith)`](#replaceresulttransformerreplacewhat-replacewith)
|
73 | - [`replaceSubstitutionTransformer(replaceWhat, replaceWith)`](#replacesubstitutiontransformerreplacewhat-replacewith)
|
74 | - [`replaceStringTransformer(replaceWhat, replaceWith)`](#replacestringtransformerreplacewhat-replacewith)
|
75 | - [`inlineArrayTransformer(opts)`](#inlinearraytransformeropts)
|
76 | - [`splitStringTransformer(splitBy)`](#splitstringtransformersplitby)
|
77 | - [How to Contribute](#how-to-contribute)
|
78 | - [License](#license)
|
79 | - [Other ES2015 Template Tag Modules](#other-es2015-template-tag-modules)
|
80 |
|
81 |
|
82 |
|
83 | ## Introduction
|
84 |
|
85 | `common-tags` initially started out as two template tags I'd always find myself writing - one for stripping indents, and one for trimming multiline strings down to a single line. In it's prime, I was an avid user of [CoffeeScript](http://coffeescript.org), which had this behaviour by default as part of it's block strings feature. I also started out programming in Ruby, which has a similar mechanism called Heredocs.
|
86 |
|
87 | Over time, I found myself needing a few more template tags to cover edge cases - ones that supported including arrays, or ones that helped to render out tiny bits of HTML not large enough to deserve their own file or an entire template engine. So I packaged all of these up into this module.
|
88 |
|
89 | As more features were proposed, and I found myself needing a way to override the default settings to cover even more edge cases, I realized that my initial implementation wouldn't be easy to scale.
|
90 |
|
91 | So I re-wrote this module on top of a core architecture that makes use of transformer plugins which can be composed, imported independently and re-used.
|
92 |
|
93 | ## Why You Should Care
|
94 |
|
95 | Tagged templates in ES2015 are a welcome feature. But, they have their downsides. One such downside is that they preserve all whitespace by default - which makes multiline strings in source code look terrible.
|
96 |
|
97 | Source code is not just for computers to interpret. Humans have to read it too 😁. If you care at all about how neat your source code is, or come from a [CoffeeScript](http://coffeescript.org/) background and miss the [block string syntax](http://coffeescript.org/#strings), then you will love `common-tags`, as it was initially intended to bring this feature "back" to JS since it's [initial commit](https://github.com/declandewet/common-tags/commit/2595288d6c276439d98d1bcbbb0aa113f4f7cd86).
|
98 |
|
99 | `common-tags` also [exposes a means of composing pipelines of dynamic transformer plugins](#plugin-transformers). As someone with a little experience writing tagged templates, I can admit that it is often the case that one tag might need to do the same thing as another tag before doing any further processing; for example - a typical tag that renders out HTML could strip initial indents first, then worry about handling character escapes. Both steps could easily be useful as their own separate template tags, but there isn't an immediately obvious way of composing the two together for maximum re-use. `common-tags` offers not [one](#tail-processing), but [two](#plugin-pipeline) ways of doing this.
|
100 |
|
101 | Furthermore, I try to keep this project as transparently stable and updated as frequently as I possibly can. As you may have already seen by the [project status table](#project-status), `common-tags` is linted, well tested, tests are well covered, tests pass on both Unix and Windows operating systems, the popularity bandwidth is easily referenced and dependency health is in plain sight 😄. `common-tags` is also already [used in production on a number of proprietary sites and dependent projects](#see-who-is-using-common-tags), and [contributions are always welcome](#how-to-contribute), as are [suggestions](issues).
|
102 |
|
103 | ## See Who Is Using `common-tags`
|
104 |
|
105 | - **[Slack](https://slack.com/)** ([ref](https://slack.com/libs/desktop))
|
106 | - **[Discord](https://discordapp.com)** ([ref](https://discordapp.com/acknowledgements))
|
107 | - **[CircleCI](https://circleci.com)** ([ref](https://circleci.com/docs/2.0/open-source/))
|
108 | - **[Confluent](https://www.confluent.io/)** ([ref](https://www.confluent.io/third_party_software/))
|
109 | - **[Tessel](https://tessel.io/)** ([ref](https://github.com/tessel/t2-cli/blob/575ddb23f432d10f86b76f5cdca866d1146dedf5/package.json#L56))
|
110 | - **[Ember.js](https://www.emberjs.com/)** ([ref](https://github.com/emberjs/ember.js/blob/cacefee49ea4be2621a0ced3e4ceb0010d6cd841/package.json#L93))
|
111 | - **[Angular](https://angularjs.org/)** ([ref](https://github.com/angular/angular-cli/blob/90e2e805aae6e0bd2e00e52063221736a8d9cb0c/package.json#L50))
|
112 | - **[Prettier](https://prettier.io/)** ([ref](https://github.com/prettier/prettier-eslint/blob/49b762b57b7e7af3b06bd933050c614a91b6742d/package.json#L18))
|
113 | - **[Apollo](https://www.apollographql.com)** ([ref](https://github.com/apollographql/apollo-codegen/blob/b9b9a2afd851fa3cba786b26684b26378b1a6f53/package.json#L48))
|
114 | - **[Workbox](https://developers.google.com/web/tools/workbox/)** ([ref](https://github.com/GoogleChrome/workbox/blob/d391a0cb51b3e89121c5274fb15f05988233b57e/package.json#L64))
|
115 | - **[Gatsby](https://www.gatsbyjs.org/)** ([ref](https://github.com/gatsbyjs/gatsby/blob/3af191c9961b6da1cc04e9cb0a03787af25878db/packages/gatsby-cli/package.json#L16))
|
116 | - **[Storybook](https://storybook.js.org/)** ([ref](https://github.com/storybooks/storybook/blob/c275e5c508714bd1a49342e51ddf00bbdb54d277/app/react/package.json#L46))
|
117 | - **[Cypress](https://www.cypress.io/)** ([ref](https://github.com/cypress-io/cypress/blob/5d761630f233abb30b9b2e3fede9a4c4887cf880/cli/package.json#L44))
|
118 | - **[stylelint](http://stylelint.io/)** ([ref](https://github.com/stylelint/stylelint/blob/5dc5db5599a00cabc875cf99c56d60f93fbbbd2d/package.json#L82))
|
119 | - **[pnpm](https://pnpm.js.org/)** ([ref](https://github.com/pnpm/pnpm/blob/36be3d3f0c75992a1f3ff14b60c99115547d0fcc/package.json#L36))
|
120 | - **[jss](http://cssinjs.org/)** ([ref](https://github.com/cssinjs/jss/blob/7b9c1222893495c585b4b61d7ca9af05077cefec/package.json#L44))
|
121 |
|
122 | ## Installation
|
123 |
|
124 | ### Requirements
|
125 |
|
126 | The official recommendation for running `common-tags` is as follows:
|
127 |
|
128 | - [Node.js](https://nodejs.org/en/download/) v5.0.0 or higher
|
129 | - In order to use `common-tags`, your environment will also need to support ES2015 tagged templates ([pssst… check Babel out](http://babeljs.io))
|
130 | - You might also want to [polyfill some features](https://github.com/zloirock/core-js) if you plan on supporting older browsers: `Array.prototype.includes`
|
131 |
|
132 | It might work with below versions of Node, but this is not a guarantee.
|
133 |
|
134 | ### Instructions
|
135 |
|
136 | `common-tags` is a [Node](https://nodejs.org/) module. So, as long as you have Node.js and NPM installed, installing `common-tags` is as simple as running this in a terminal at the root of your project:
|
137 |
|
138 | ```sh
|
139 | npm install common-tags
|
140 | ```
|
141 |
|
142 | ## Usage
|
143 |
|
144 | ### Imports
|
145 |
|
146 | Like all modules, `common-tags` begins with an `import`. In fact, `common-tags` supports two styles of import:
|
147 |
|
148 | **Named imports:**
|
149 |
|
150 | ```js
|
151 | import {stripIndent} from 'common-tags'
|
152 | ```
|
153 |
|
154 | **Direct module imports:**
|
155 |
|
156 | *(Useful if your bundler doesn't support [tree shaking](https://medium.com/@roman01la/dead-code-elimination-and-tree-shaking-in-javascript-build-systems-fb8512c86edf#.p30lbjm94) but you still want to only include modules you need).*
|
157 |
|
158 | ```js
|
159 | import stripIndent from 'common-tags/lib/stripIndent'
|
160 | ```
|
161 |
|
162 | ### Available Tags
|
163 |
|
164 | `common-tags` exports a bunch of wonderful pre-cooked template tags for your eager consumption. They are as follows:
|
165 |
|
166 | #### `html`
|
167 |
|
168 | ##### Aliases: `source`, `codeBlock`
|
169 |
|
170 | You'll often find that you might want to include an array in a template. Typically, doing something like `${array.join(', ')}` would work - but what if you're printing a list of items in an HTML template and want to maintain the indentation? You'd have to count the spaces manually and include them in the `.join()` call - which is a bit *ugly* for my taste. This tag properly indents arrays, as well as newline characters in string substitutions, by converting them to an array split by newline and re-using the same array inclusion logic:
|
171 |
|
172 | ```js
|
173 | import {html} from 'common-tags'
|
174 | let fruits = ['apple', 'orange', 'watermelon']
|
175 | html`
|
176 | <div class="list">
|
177 | <ul>
|
178 | ${fruits.map(fruit => `<li>${fruit}</li>`)}
|
179 | ${'<li>kiwi</li>\n<li>guava</li>'}
|
180 | </ul>
|
181 | </div>
|
182 | `
|
183 | ```
|
184 |
|
185 | Outputs:
|
186 |
|
187 | ```html
|
188 | <div class="list">
|
189 | <ul>
|
190 | <li>apple</li>
|
191 | <li>orange</li>
|
192 | <li>watermelon</li>
|
193 | <li>kiwi</li>
|
194 | <li>guava</li>
|
195 | </ul>
|
196 | </div>
|
197 | ```
|
198 |
|
199 | #### `safeHtml`
|
200 |
|
201 | A tag very similar to `html` but it does safe HTML escaping for strings coming from substitutions. When combined with regular `html` tag, you can do basic HTML templating that is safe from XSS (Cross-Site Scripting) attacks.
|
202 |
|
203 | ```js
|
204 | import {html, safeHtml} from 'common-tags'
|
205 | let userMessages = ['hi', 'what are you up to?', '<script>alert("something evil")</script>']
|
206 | html`
|
207 | <div class="chat-list">
|
208 | <ul>
|
209 | ${userMessages.map(message => safeHtml`<li>${message}</li>`)}
|
210 | </ul>
|
211 | </div>
|
212 | `
|
213 | ```
|
214 |
|
215 | Outputs:
|
216 |
|
217 | ```html
|
218 | <div class="chat-list">
|
219 | <ul>
|
220 | <li>hi</li>
|
221 | <li>what are you up to?</li>
|
222 | <li><script>alert("something evil")</script></li>
|
223 | </ul>
|
224 | </div>
|
225 | ```
|
226 |
|
227 | #### `oneLine`
|
228 |
|
229 | Allows you to keep your single-line strings under 80 characters without resorting to crazy string concatenation.
|
230 |
|
231 | ```js
|
232 | import {oneLine} from 'common-tags'
|
233 |
|
234 | oneLine`
|
235 | foo
|
236 | bar
|
237 | baz
|
238 | `
|
239 | // "foo bar baz"
|
240 | ```
|
241 |
|
242 | #### `oneLineTrim`
|
243 |
|
244 | Allows you to keep your single-line strings under 80 characters while trimming the new lines:
|
245 |
|
246 | ```js
|
247 | import {oneLineTrim} from 'common-tags'
|
248 |
|
249 | oneLineTrim`
|
250 | https://news.com/article
|
251 | ?utm_source=designernews.co
|
252 | `
|
253 | // https://news.com/article?utm_source=designernews.co
|
254 | ```
|
255 |
|
256 | #### `stripIndent`
|
257 |
|
258 | If you want to strip the initial indentation from the beginning of each line in a multiline string:
|
259 |
|
260 | ```js
|
261 | import {stripIndent} from 'common-tags'
|
262 |
|
263 | stripIndent`
|
264 | This is a multi-line string.
|
265 | You'll ${verb} that it is indented.
|
266 | We don't want to output this indentation.
|
267 | But we do want to keep this line indented.
|
268 | `
|
269 | // This is a multi-line string.
|
270 | // You'll notice that it is indented.
|
271 | // We don't want to output this indentation.
|
272 | // But we do want to keep this line indented.
|
273 | ```
|
274 |
|
275 | Important note: this tag will not indent multiline strings coming from the substitutions. If you want that behavior, use the `html` tag (aliases: `source`, `codeBlock`).
|
276 |
|
277 | #### `stripIndents`
|
278 |
|
279 | If you want to strip *all* of the indentation from the beginning of each line in a multiline string:
|
280 |
|
281 | ```js
|
282 | import {stripIndents} from 'common-tags'
|
283 |
|
284 | stripIndents`
|
285 | This is a multi-line string.
|
286 | You'll ${verb} that it is indented.
|
287 | We don't want to output this indentation.
|
288 | We don't want to keep this line indented either.
|
289 | `
|
290 | // This is a multi-line string.
|
291 | // You'll notice that it is indented.
|
292 | // We don't want to output this indentation.
|
293 | // We don't want to keep this line indented either.
|
294 | ```
|
295 |
|
296 | #### `inlineLists`
|
297 |
|
298 | Allows you to inline an array substitution as a list:
|
299 |
|
300 | ```js
|
301 | import {inlineLists} from 'common-tags'
|
302 |
|
303 | inlineLists`
|
304 | I like ${['apples', 'bananas', 'watermelons']}
|
305 | They're good!
|
306 | `
|
307 | // I like apples bananas watermelons
|
308 | // They're good!
|
309 | ```
|
310 |
|
311 | #### `oneLineInlineLists`
|
312 |
|
313 | Allows you to inline an array substitution as a list, rendered out on a single line:
|
314 |
|
315 | ```js
|
316 | import {oneLineInlineLists} from 'common-tags'
|
317 |
|
318 | oneLineInlineLists`
|
319 | I like ${['apples', 'bananas', 'watermelons']}
|
320 | They're good!
|
321 | `
|
322 | // I like apples bananas watermelons They're good!
|
323 | ```
|
324 |
|
325 | #### `commaLists`
|
326 |
|
327 | Allows you to inline an array substitution as a comma-separated list:
|
328 |
|
329 | ```js
|
330 | import {commaLists} from 'common-tags'
|
331 |
|
332 | commaLists`
|
333 | I like ${['apples', 'bananas', 'watermelons']}
|
334 | They're good!
|
335 | `
|
336 | // I like apples, bananas, watermelons
|
337 | // They're good!
|
338 | ```
|
339 |
|
340 | #### `commaListsOr`
|
341 |
|
342 | Allows you to inline an array substitution as a comma-separated list, the last of which is preceded by the word "or":
|
343 |
|
344 | ```js
|
345 | import {commaListsOr} from 'common-tags'
|
346 |
|
347 | commaListsOr`
|
348 | I like ${['apples', 'bananas', 'watermelons']}
|
349 | They're good!
|
350 | `
|
351 | // I like apples, bananas or watermelons
|
352 | // They're good!
|
353 | ```
|
354 |
|
355 | #### `commaListsAnd`
|
356 |
|
357 | Allows you to inline an array substitution as a comma-separated list, the last of which is preceded by the word "and":
|
358 |
|
359 | ```js
|
360 | import {commaListsAnd} from 'common-tags'
|
361 |
|
362 | commaListsAnd`
|
363 | I like ${['apples', 'bananas', 'watermelons']}
|
364 | They're good!
|
365 | `
|
366 | // I like apples, bananas and watermelons
|
367 | // They're good!
|
368 | ```
|
369 |
|
370 | #### `oneLineCommaLists`
|
371 |
|
372 | Allows you to inline an array substitution as a comma-separated list, and is rendered out on to a single line:
|
373 |
|
374 | ```js
|
375 | import {oneLineCommaLists} from 'common-tags'
|
376 |
|
377 | oneLineCommaLists`
|
378 | I like ${['apples', 'bananas', 'watermelons']}
|
379 | They're good!
|
380 | `
|
381 | // I like apples, bananas or watermelons They're good!
|
382 | ```
|
383 |
|
384 | #### `oneLineCommaListsOr`
|
385 |
|
386 | Allows you to inline an array substitution as a comma-separated list, the last of which is preceded by the word "or", and is rendered out on to a single line:
|
387 |
|
388 | ```js
|
389 | import {oneLineCommaListsOr} from 'common-tags'
|
390 |
|
391 | oneLineCommaListsOr`
|
392 | I like ${['apples', 'bananas', 'watermelons']}
|
393 | They're good!
|
394 | `
|
395 | // I like apples, bananas or watermelons They're good!
|
396 | ```
|
397 |
|
398 | #### `oneLineCommaListsAnd`
|
399 |
|
400 | Allows you to inline an array substitution as a comma-separated list, the last of which is preceded by the word "and", and is rendered out on to a single line:
|
401 |
|
402 | ```js
|
403 | import {oneLineCommaListsAnd} from 'common-tags'
|
404 |
|
405 | oneLineCommaListsAnd`
|
406 | I like ${['apples', 'bananas', 'watermelons']}
|
407 | They're good!
|
408 | `
|
409 | // I like apples, bananas and watermelons They're good!
|
410 | ```
|
411 |
|
412 | ## Advanced Usage
|
413 |
|
414 | ### Tail Processing
|
415 |
|
416 | It's possible to pass the output of a tagged template to another template tag in pure ES2015+:
|
417 |
|
418 | ```js
|
419 | import {oneLine} from 'common-tags'
|
420 |
|
421 | oneLine`
|
422 | ${String.raw`
|
423 | foo
|
424 | bar\nbaz
|
425 | `}
|
426 | `
|
427 | // "foo bar\nbaz"
|
428 | ```
|
429 |
|
430 | We can make this neater. Every tag `common-tags` exports can delay execution if it receives a function as it's first argument. This function is assumed to be a template tag, and is called via an intermediary tagging process before the result is passed back to our tag. Use it like so (this code is equivalent to the previous code block):
|
431 |
|
432 | ```js
|
433 | import {oneLine} from 'common-tags'
|
434 |
|
435 | oneLine(String.raw)`
|
436 | foo
|
437 | bar\nbaz
|
438 | `
|
439 | // "foo bar\nbaz"
|
440 | ```
|
441 |
|
442 | ### Using Tags on Regular String Literals
|
443 |
|
444 | Sometimes you might want to use a tag on a normal string (e.g. for stripping the indentation). For that purpose just call a tag as a function with the passed string:
|
445 |
|
446 | ```js
|
447 | import {stripIndent} from 'common-tags'
|
448 |
|
449 | stripIndent(" foo\n bar")
|
450 | // "foo\n bar"
|
451 | ```
|
452 |
|
453 | ### Type Definitions
|
454 |
|
455 | There are third-party type definitions for `common-tags` on [npm](https://www.npmjs.com/package/@types/common-tags). Just install them like so:
|
456 |
|
457 | ```sh
|
458 | npm install @types/common-tags
|
459 | ```
|
460 |
|
461 | Please note that these type definitions are not officially maintained by the authors of
|
462 | `common-tags` - they are maintained by the TypeScript community.
|
463 |
|
464 | ### Make Your Own Template Tag
|
465 |
|
466 | `common-tags` exposes an interface that allows you to painlessly create your own template tags.
|
467 |
|
468 | #### Class is in Session: TemplateTag
|
469 |
|
470 | `common-tags` exports a `TemplateTag` class. This class is the foundation of `common-tags`. The concept of the class works on the premise that transformations occur on a template either when the template is finished being processed (`onEndResult`), or when the tag encounters a string (`onString`) or a substitution (`onSubstitution`). Any tag produced by this class supports [tail processing](#tail-processing).
|
471 |
|
472 | The easiest tag to create is a tag that does nothing:
|
473 |
|
474 | ```js
|
475 | import {TemplateTag} from 'common-tags'
|
476 |
|
477 | const doNothing = new TemplateTag()
|
478 |
|
479 | doNothing`foo bar`
|
480 | // 'foo bar'
|
481 | ```
|
482 |
|
483 | #### The Anatomy of a Transformer
|
484 |
|
485 | `TemplateTag` receives either an array or argument list of `transformers`. A `transformer` is just a plain object with three optional methods - `onString`, `onSubstitution` and `onEndResult` - it looks like this:
|
486 |
|
487 | ```js
|
488 | {
|
489 | onString (str) {
|
490 | // optional. Called when the tag encounters a string.
|
491 | // (a string is whatever's not inside "${}" in your template literal)
|
492 | // `str` is the value of the current string
|
493 | },
|
494 | onSubstitution (substitution, resultSoFar) {
|
495 | // optional. Called when the tag encounters a substitution.
|
496 | // (a substitution is whatever's inside "${}" in your template literal)
|
497 | // `substitution` is the value of the current substitution
|
498 | // `resultSoFar` is the end result up to the point of this substitution
|
499 | },
|
500 | onEndResult (endResult) {
|
501 | // optional. Called when all substitutions have been parsed
|
502 | // `endResult` is the final value.
|
503 | }
|
504 | }
|
505 | ```
|
506 |
|
507 | #### Plugin Transformers
|
508 |
|
509 | You can wrap a transformer in a function that receives arguments in order to create a dynamic plugin:
|
510 |
|
511 | ```js
|
512 | const substitutionReplacer = (oldValue, newValue) => ({
|
513 | onSubstitution(substitution, resultSoFar) {
|
514 | if (substitution === oldValue) {
|
515 | return newValue
|
516 | }
|
517 | return substitution
|
518 | }
|
519 | })
|
520 |
|
521 | const replaceFizzWithBuzz = new TemplateTag(substitutionReplacer('fizz', 'buzz'))
|
522 |
|
523 | replaceFizzWithBuzz`foo bar ${"fizz"}`
|
524 | // "foo bar buzz"
|
525 | ```
|
526 |
|
527 | > **note** - if you call `new TemplateTag(substitutionReplacer)`, `substitutionReplacer` will automatically be initiated with no arguments.
|
528 |
|
529 | #### Plugin Pipeline
|
530 |
|
531 | You can pass a list of transformers, and `TemplateTag` will call them on your tag in the order they are specified:
|
532 |
|
533 | ```js
|
534 | // note: passing these as an array also works
|
535 | const replace = new TemplateTag(
|
536 | substitutionReplacer('fizz', 'buzz'),
|
537 | substitutionReplacer('foo', 'bar')
|
538 | )
|
539 |
|
540 | replace`${"foo"} ${"fizz"}`
|
541 | // "bar buzz"
|
542 | ```
|
543 |
|
544 | When multiple transformers are passed to `TemplateTag`, they will be iterated three times - first, all transformer `onString` methods will be called. Once they are done processing, `onSubstitution` methods will be called. Finally, all transformer `onEndResult` methods will be called.
|
545 |
|
546 | #### Returning Other Values from a Transformer
|
547 |
|
548 | This is super easy. Transformers are just objects, after all. They have full access to `this`:
|
549 |
|
550 | ```js
|
551 | const listSubs = {
|
552 | onString(str) {
|
553 | this.ctx = this.ctx || { strings: [], subs: [] }
|
554 | this.ctx.strings.push(str);
|
555 | return str
|
556 | },
|
557 | onSubstitution(sub, res) {
|
558 | this.ctx.subs.push({ sub, precededBy: res })
|
559 | return sub
|
560 | },
|
561 | onEndResult(res) {
|
562 | return this.ctx
|
563 | }
|
564 | }
|
565 |
|
566 | const toJSON = {
|
567 | onEndResult(res) {
|
568 | return JSON.stringify(res, null, 2)
|
569 | }
|
570 | }
|
571 |
|
572 | const log = {
|
573 | onEndResult(res) {
|
574 | console.log(res)
|
575 | return res
|
576 | }
|
577 | }
|
578 |
|
579 | const process = new TemplateTag([listSubs, toJSON, log])
|
580 |
|
581 | process`
|
582 | foo ${'bar'}
|
583 | fizz ${'buzz'}
|
584 | `
|
585 | // {
|
586 | // "strings": [
|
587 | // "\n foo ",
|
588 | // "\n foo bar\n fizz ",
|
589 | // "\n"
|
590 | // ],
|
591 | // "subs": [
|
592 | // {
|
593 | // "sub": "bar",
|
594 | // "precededBy": "\n foo "
|
595 | // },
|
596 | // {
|
597 | // "sub": "buzz",
|
598 | // "precededBy": "\n foo bar\n fizz "
|
599 | // }
|
600 | // ]
|
601 | // }
|
602 | ```
|
603 |
|
604 | #### List of Built-in Transformers
|
605 |
|
606 | Since `common-tags` is built on the foundation of this TemplateTag class, it comes with its own set of built-in transformers:
|
607 |
|
608 | ##### `trimResultTransformer([side])`
|
609 |
|
610 | Trims the whitespace surrounding the end result. Accepts an optional `side` (can be `"start"` or `"end"` or alternatively `"left"` or `"right"`) that when supplied, will only trim whitespace from that side of the string.
|
611 |
|
612 | ##### `stripIndentTransformer([type='initial'])`
|
613 |
|
614 | Strips the indents from the end result. Offers two types: `all`, which removes all indentation from each line, and `initial`, which removes the shortest indent level from each line. Defaults to `initial`.
|
615 |
|
616 | ##### `replaceResultTransformer(replaceWhat, replaceWith)`
|
617 |
|
618 | Replaces a value or pattern in the end result with a new value. `replaceWhat` can be a string or a regular expression, `replaceWith` is the new value.
|
619 |
|
620 | ##### `replaceSubstitutionTransformer(replaceWhat, replaceWith)`
|
621 |
|
622 | Replaces the result of all substitutions (results of calling `${ ... }`) with a new value. Same as for `replaceResultTransformer`, `replaceWhat` can be a string or regular expression and `replaceWith` is the new value.
|
623 |
|
624 | ##### `replaceStringTransformer(replaceWhat, replaceWith)`
|
625 |
|
626 | Replaces the result of all strings (what's not in `${ ... }`) with a new value. Same as for `replaceResultTransformer`, `replaceWhat` can be a string or regular expression and `replaceWith` is the new value.
|
627 |
|
628 | ##### `inlineArrayTransformer(opts)`
|
629 |
|
630 | Converts any array substitutions into a string that represents a list. Accepts an options object:
|
631 |
|
632 | ```js
|
633 | opts = {
|
634 | separator: ',', // what to separate each item with (always followed by a space)
|
635 | conjunction: 'and', // replace the last separator with this value
|
636 | serial: true // should the separator be included before the conjunction? As in the case of serial/oxford commas
|
637 | }
|
638 | ```
|
639 |
|
640 | ##### `splitStringTransformer(splitBy)`
|
641 |
|
642 | Splits a string substitution into an array by the provided `splitBy` substring, **only** if the string contains the `splitBy` substring.
|
643 |
|
644 | ## How to Contribute
|
645 |
|
646 | Please see the [Contribution Guidelines](contributing.md).
|
647 |
|
648 | ## License
|
649 |
|
650 | MIT. See [license.md](license.md).
|
651 |
|
652 | ## Other ES2015 Template Tag Modules
|
653 |
|
654 | If `common-tags` doesn't quite fit your bill, and you just can't seem to find what you're looking for - perhaps these might be of use to you?
|
655 |
|
656 | - [tage](https://www.npmjs.com/package/tage) - make functions work as template tags too
|
657 | - [is-tagged](https://www.npmjs.com/package/is-tagged) - Check whether a function call is initiated by a tagged template string or invoked in a regular way
|
658 | - [es6-template-strings](https://www.npmjs.com/package/es6-template-strings) - Compile and resolve template strings notation as specified in ES6
|
659 | - [t7](https://github.com/trueadm/t7) - A light-weight virtual-dom template library
|
660 | - [html-template-tag](https://www.npmjs.com/package/html-template-tag) - ES6 Tagged Template for compiling HTML template strings.
|
661 | - [clean-tagged-string](https://www.npmjs.com/package/clean-tagged-string) - A simple utility function to clean ES6 template strings.
|
662 | - [multiline-tag](https://www.npmjs.com/package/multiline-tag) - Tags for template strings making them behave like coffee multiline strings
|
663 | - [deindent](https://www.npmjs.com/package/deindent) - ES6 template string helper for deindentation.
|
664 | - [heredoc-tag](https://www.npmjs.com/package/heredoc-tag) - Heredoc helpers for ES2015 template strings
|
665 | - [regx](https://www.npmjs.com/package/regx) - Tagged template string regular expression compiler.
|
666 | - [regexr](https://www.npmjs.org/package/regexr) - Provides an ES6 template tag function that makes it easy to compose regexes out of template strings without double-escaped hell.
|
667 | - [url-escape-tag](https://www.npmjs.com/package/url-escape-tag) - A template tag for escaping url parameters based on ES2015 tagged templates.
|
668 | - [shell-escape-tag](https://www.npmjs.com/package/shell-escape-tag) - An ES6+ template tag which escapes parameters for interpolation into shell commands.
|
669 | - [sql-tags](https://www.npmjs.com/package/sql-tags) - ES6 tagged template string functions for SQL statements.
|
670 | - [sql-tag](https://www.npmjs.com/package/sql-tag) - A template tag for writing elegant sql strings.
|
671 | - [sequelize-sql-tag](https://www.npmjs.com/package/sequelize-sql-tag) - A sequelize plugin for sql-tag
|
672 | - [pg-sql-tag](https://www.npmjs.com/package/pg-sql-tag) - A pg plugin for sql-tag
|
673 | - [sql-template-strings](https://www.npmjs.com/package/sql-template-strings) - ES6 tagged template strings for prepared statements with mysql and postgres
|
674 | - [sql-composer](https://www.npmjs.com/package/sql-composer) - Composable SQL template strings for Node.js
|
675 | - [pg-template-tag](https://www.npmjs.com/package/pg-template-tag) - ECMAScript 6 (2015) template tag function to write queries for node-postgres.
|
676 | - [digraph-tag](https://www.npmjs.com/package/digraph-tag) - ES6 string template tag for quickly generating directed graph data
|
677 | - [es2015-i18n-tag](https://www.npmjs.com/package/es2015-i18n-tag) - ES2015 template literal tag for i18n and l10n translation and localization
|