1.3.0 • Published 3 years ago
template-processor v1.3.0
template-processor
A lightweight class for generating markup from a template and some data.
Install
npm install template-processor
Example
Given the following document,
<!doctype html>
<html>
<body>
<template>
<a href="{{ url }}">{{ text }}</a>
</template>
</body>
</html>
The code below (JavaScript or Typescript) will append the following markup to the body.
<a href="https://www.example.com/" rel="external">AN EXAMPLE</a>
API:
- Import the
Processor
class. - The constructor’s
instructions
argument must be a function returningvoid
. - The constructor’s
instructions_async
argument, if provided, must be an asynchronous function returning aPromise<void>
. (If providinginstructions_async
, theinstructions
argument is still required. It could be an empty function or a fallback to the async.) - The
process
method returns aDocumentFragment
. - The asynchronous
processAsync
method returns aPromise<DocumentFragment>
.
JavaScript
// import the module
const {Processor} = require('template-processor')
// get your own template & write your own instructions
let template = document.querySelector('template')
function instructions(frag, data, opts) {
frag.querySelector('a').href = data.url
frag.querySelector('a').textContent = (opts.uppercase) ? data.text.toUpperCase() : data.text
if (data.url.slice(0,4) === 'http') {
frag.querySelector('a').setAttribute('rel', 'external')
}
}
// if your instructions uses I/O, you can write an asynchronous function
async function instructionsAsync(frag, data, opts) {
await doSomeAsyncStuff();
}
// construct a new processor with the stuff you wrote
let my_processor = new Processor(template, instructions)
// optionally provide the async instructions
my_processor = new Processor(template, instructions, instructionsAsync)
// process some data synchronously
let snippet = my_processor.process({
url: 'https://www.example.com/',
text: 'an example',
}, { uppercase: true })
document.body.append(snippet)
// process some data asynchronously
my_processor.processAsync({
url: 'https://www.example.com/',
text: 'an example',
}, { uppercase: true }).then((snippet) => {
document.body.append(snippet)
})
// you can also pass in Promises for the data and options
my_processor.processAsync(Promise.resolve({
url: 'https://www.example.com/',
text: 'an example',
}), Promise.resolve({ uppercase: true })).then((snippet) => {
document.body.append(snippet)
})
TypeScript
// import the module
import {Processor} from 'template-processor'
// get your own template & write your own instructions
type DataType = { url: string; text: string; }
type OptsType = { uppercase?: boolean; }
let template: HTMLTemplateElement = document.querySelector('template') !
function instructions(frag: DocumentFragment, data: DataType, opts: OptsType): void {
frag.querySelector('a').href = data.url
frag.querySelector('a').textContent = (opts.uppercase) ? data.text.toUpperCase() : data.text
if (data.url.slice(0,4) === 'http') {
frag.querySelector('a').setAttribute('rel', 'external')
}
}
// if your instructions uses I/O, you can write an asynchronous function
async function instructionsAsync(frag: DocumentFragment, data: DataType, opts: OptsType): Promise<void> {
await doSomeAsyncStuff();
}
// construct a new processor with the stuff you wrote
let my_processor: Processor<DataType, OptsType> = new Processor(template, instructions)
// optionally provide the async instructions
my_processor = new Processor(template, instructions, instructionsAsync)
// process some data synchronously
let snippet: DocumentFragment = my_processor.process({
url: 'https://www.example.com/',
text: 'an example',
}, { uppercase: true })
document.body.append(snippet)
// process some data asynchronously
my_processor.processAsync({
url: 'https://www.example.com/',
text: 'an example',
}, { uppercase: true }).then((snippet) => {
document.body.append(snippet)
})
// you can also pass in Promises for the data and options
let data: Promise<DataType> = Promise.resolve({
url: 'https://www.example.com/',
text: 'an example',
})
let opts: Promise<OptsType> = Promise.resolve({ uppercase: true })
my_processor.processAsync(data, opts).then((snippet) => {
document.body.append(snippet)
})
Why?
The point is to have one template and one instruction, but tons of data.
const dataset = [
{ "name": "twitter" , "url": "//twitter.com/god" , "text": "Follow God on Twitter" },
{ "name": "google" , "url": "//plus.google.com/god", "text": "Follow God on Google+" },
{ "name": "facebook", "url": "//facebook.com/god" , "text": "Like God on Facebook" },
{ "name": "linkedin", "url": "//linkedin.com/god" , "text": "Connect with God on LinkedIn" },
{ "name": "youtube" , "url": "//youtube.com/god" , "text": "Watch God on YouTube" },
// even more and more
]
const document = createDocument`
<html>
<body>
<h1>Social Media Links</h1>
<ul class="c-LinkList">
<template>
<li class="c-LinkList__Item">
<a class="c-LinkList__Link" href="{{ url }}">
<i class="{{ name }}"></i>
<slot name="text">{{ text }}</slot>
</a>
</li>
</template>
</ul>
</body>
</html>
`
let processor = new Processor(document.querySelector('ul > template'), (frag, data, opts) => {
frag.querySelector('a.c-LinkList__Link').href = data.url
frag.querySelector('i' ).className = `icon icon-${data.name}`
frag.querySelector('slot[name="text"]' ).textContent = data.text
})
// sync way:
document.querySelector('ul').append(...dataset.map((data) => processor.process(data)))
// async way (promises):
Promise.all(dataset.map((data) => processor.processAsync(data)))
.then((frags) => document.querySelector('ul').append(...frags))
// async way (await):
document.querySelector('ul').append(...await Promise.all(dataset.map((data) => processor.processAsync(data))))
Starting in v1.2, we can do the above much more efficiently with two new static methods:
Processor.populateList
and Processor.populateListAsync
.
They check for a <template>
inside the list and ensure it has the correct markup structure.
// sync way:
Processor.populateList(document.querySelector('ul'), (frag, data, opts) => {
frag.querySelector('a.c-LinkList__Link').href = data.url
frag.querySelector('i' ).className = `icon icon-${data.name}`
frag.querySelector('slot[name="text"]' ).textContent = data.text
}, dataset)
// async way:
Processor.populateListAsync(document.querySelector('ul'), async (frag, data, opts) => {
frag.querySelector('a.c-LinkList__Link').href = data.url
frag.querySelector('i' ).className = `icon icon-${data.name}`
frag.querySelector('slot[name="text"]' ).textContent = data.text
}, Promise.resolve(dataset))
2.0.0-beta.0
3 years ago
1.3.0
3 years ago
2.0.0-alpha.0
4 years ago
1.2.0
5 years ago
1.2.0-beta.1
5 years ago
1.2.0-beta.0
5 years ago
1.1.0
5 years ago
1.1.0-beta.0
5 years ago
1.0.1
6 years ago
1.0.0
6 years ago
0.1.0
6 years ago