From 33171a749162685e42650f82041cd2af0136718d Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Sun, 18 Jun 2017 17:42:21 +0200 Subject: feat(posts): render posts as markdown --- package.json | 3 ++- src/index.js | 4 +++- src/modules/posts.js | 15 ++++++++++++++- src/views/post.html | 2 +- test/index.test.js | 2 +- yarn.lock | 28 ++++++++++++++++++++++++++++ 6 files changed, 49 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 03179cd..e25d390 100644 --- a/package.json +++ b/package.json @@ -29,9 +29,10 @@ "supertest": "^3.0.0" }, "dependencies": { + "gray-matter": "^2.1.1", "koa": "^2.2.0", "koa-nunjucks-next": "^1.1.3", "koa-router": "^7.2.1", - "gray-matter": "^2.1.1" + "markdown-it": "^8.3.1" } } diff --git a/src/index.js b/src/index.js index 07d7249..fce4c09 100644 --- a/src/index.js +++ b/src/index.js @@ -24,8 +24,10 @@ router.get('/', async function (ctx) { router.get('/post/:filename', async function (ctx) { ctx.assert(posts.has(ctx.params.filename), 404, 'Post not found') + const post = posts.get(ctx.params.filename) + post.body = Posts.render(post) await ctx.render('post', { - post: posts.get(ctx.params.filename) + post: post }) }) diff --git a/src/modules/posts.js b/src/modules/posts.js index 011292b..cba2372 100644 --- a/src/modules/posts.js +++ b/src/modules/posts.js @@ -3,12 +3,20 @@ const fs = require('fs') const path = require('path') const matter = require('gray-matter') +const Markdown = require('markdown-it') const grayMatterOptions = { lang: 'toml', delims: '+++' } +const markdownOptions = { + html: true, + typographer: true +} + +const markdown = new Markdown(markdownOptions) + function* lowercaseKeys (iterator) { for (let [k, v] of iterator) { yield [String(k).toLowerCase(), v] @@ -28,6 +36,10 @@ function getTitle (file) { return path.basename(file.path, path.extname(file.path)) } +function render (post) { + return markdown.render(post.content) +} + function get (filename) { const fileMatter = matter.read(filename, grayMatterOptions) fileMatter.basename = getTitle(fileMatter) @@ -59,5 +71,6 @@ function toTags (posts) { module.exports = { get, getFolder, - toTags + toTags, + render } diff --git a/src/views/post.html b/src/views/post.html index fcc4dbd..81f7e3d 100644 --- a/src/views/post.html +++ b/src/views/post.html @@ -1,3 +1,3 @@ {{ post.data.title }} -{{ post.content }} +{{ post.body | safe }} diff --git a/test/index.test.js b/test/index.test.js index a81dbb6..e13e52c 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -18,7 +18,7 @@ test('post', t => { return request(app.listen()) .get('/post/testfile') .expect(200) - .expect(/Lorem ipsum/) + .expect(/