-
Notifications
You must be signed in to change notification settings - Fork 61.6k
/
Copy pathindex.js
52 lines (46 loc) · 1.65 KB
/
index.js
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
import { renderLiquid } from './liquid/index.js'
import { renderMarkdown, renderUnified } from './unified/index.js'
import { engine } from './liquid/engine.js'
const globalCache = new Map()
// parse multiple times because some templates contain more templates. :]
export async function renderContent(template = '', context = {}, options = {}) {
// If called with a falsy template, it can't ever become something
// when rendered. We can exit early to save some pointless work.
if (!template) return template
let cacheKey = null
if (options && options.cache) {
if (!context) throw new Error("If setting 'cache' in options, the 'context' must be set too")
if (typeof options.cache === 'function') {
cacheKey = options.cache(template, context)
} else {
cacheKey = getDefaultCacheKey(template, context)
}
if (cacheKey && typeof cacheKey !== 'string') {
throw new Error('cache option must return a string if truthy')
}
if (globalCache.has(cacheKey)) {
return globalCache.get(cacheKey)
}
}
try {
template = await renderLiquid(template, context)
if (context.markdownRequested) {
const md = await renderMarkdown(template, context, options)
return md
}
const html = await renderUnified(template, context, options)
if (cacheKey) {
globalCache.set(cacheKey, html)
}
return html
} catch (error) {
if (options.filename) {
console.error(`renderContent failed on file: ${options.filename}`)
}
throw error
}
}
function getDefaultCacheKey(template, context) {
return `${template}:${context.currentVersion}:${context.currentLanguage}`
}
export const liquid = engine