Extra indentation being added to markdown when inserted into a textarea

Viewed 23

I'm new to Node.js and Express and I'm trying to create a basic blog application where the blog posts are created in markdown and rendered in HTML. I'm using MongoDB with Mongoose for my database, Handlebars for my template engine, and Showdown.js to render markdown as HTML. I created a form page where I can submit new blog posts and save them to my database. I can retrieve that post from the database, render it to HTML with showdown, and return it. That all works fine.

The problem is when I want to edit the post. I retrieve the post from the database, return it to the same form I used to create it, and all the markdown gets put into a <textarea> tag using a triple-brace expression in Handlebars like so:

<textarea name="markdown">{{{post.markdown}}}</textarea>

The markdown put in the text area has been indented on each new line after the first line which wasn't in the original. Because it's indented, next time I save it, all the indented text will get wrapped in <pre> blocks when rendered to HTML.

I can't figure out where this extra indentation is coming from. My guess is that something is being encoded funky somewhere in the pipeline. It saves and renders fine when I first create the post. If I manually remove this indentation and resave it, that also works. So it's getting messed up somewhere along the way from getting retrieved from the database to placed in the Handlebars template.

Thanks for any help you can provide!

Code for the edit page route:

router.get('/edit/:slug', async (req, res) => {
    const slug = req.params.slug;

    try {
        const post = await Post.findOne({ slug: slug }).lean();
        res.render('admin/edit', { layout: 'layout-admin', title: post.title, post: post });
    }
    catch (error) {
        res.send('Blog post not found for editing.');
    }
});

Originally Entered Markdown:

Lorem ipsum dolor sit amet.

[A test link](https://www.google.com/)

Nullam ultricies eget ligula nec luctus.

Markdown Returned When Editing:

Lorem ipsum dolor sit amet.
    
    [A test link](https://www.google.com/)
    
    Nullam ultricies eget ligula nec luctus.

For reference, here is the string literal version:

"Lorem ipsum dolor sit amet.\r\n\r\n[A test link](https://www.google.com/)\r\n\r\nNullam ultricies eget ligula nec luctus."
0 Answers
Related