qwik-cms/libs/siteRenderer.js

36 lines
1.5 KiB
JavaScript

import fs from 'fs'
import njk from 'nunjucks'
import { generateContext } from './generateContext.js'
// Load in config
const ConfigFile = fs.readFileSync('./config.json')
const Config = JSON.parse(ConfigFile)
export function njkRenderer(path) {
// Read in the template
const njkFile = fs.readFileSync(path).toString()
// Pre-render it for analysis while rendering context
const prerenderedNjk = njk.renderString(njkFile)
// Generate proper context and make a final render of the template.
const context = generateContext(prerenderedNjk)
return njk.renderString(njkFile, context)
}
export function mdRenderer(path) {
// Load in the njk template and markdown
const njkFile = fs.readFileSync(`${Config.contentDir}/templates/external_md.njk`).toString()
const externalMarkdownFile = fs.readFileSync(path).toString()
// Separate the actual markdown from potential 'externalContext'
const externalMarkdown = externalMarkdownFile.replace(/^%%-\n[\S\s]*-%%\n/, "").replace(/```\w*[\s\S]*?```/g, match => match.replace(/ /g, "•"))
const externalContext = externalMarkdownFile.match(/^%%-\n[\S\s]*-%%\n/)
// Pre-render the template for analysis during context generation.
const prerenderedNjk = njk.renderString(njkFile, { externalMarkdown })
// Generate the context and add the externalMarkdown to the context, then render the template.
let context = generateContext(prerenderedNjk, externalContext)
context.externalMarkdown = externalMarkdown
return njk.renderString(njkFile, context)
}