Pass markdown from file to template in Django view

1.2k Views Asked by At

I'm trying to pass the contents of an *.md file from my Django view for rendering using Showdown (JS code below), but I get: Uncaught SyntaxError: Invalid or unexpected token:

var converter = new showdown.Converter({
    'github_flavouring': true,
    'tables': true
});
var convert = function() {
    $('#preview').html(converter.makeHtml($('{{markdown}}')));
};
convert();
1

There are 1 best solutions below

2
On BEST ANSWER

I generally prefer to use a hidden div to contain my markdown data:

<div id="markdown" style="display:none;">
    {{markdown}}
</div>

Then you can refer to this in your JavaScript code as follows:

var converter = new showdown.Converter({
    'github_flavouring': true,
    'tables': true
});
var convert = function() {
    $('#preview').html(converter.makeHtml($('#markdown').text()));
};
convert();

[Edit] For ES6, You could also try to use backticks (`) to encapsulate your markdown data, which would make it a multi-line string but since markdown uses backticks to highlight code, this would cause problems (unless you're sure you will never have code blocks in your markdown data).