I'm trying to create a two column html page that uses django as a manager for a blog. The body of the post has a TextField that is converted to markdown and sent to the html:
class Post(models.Model):
title = models.CharField(max_length=67, unique=True)
body = models.TextField()
body_md = models.TextField(editable=False, blank=True, null=True)
def save(self):
selft.body_md = markdown2.markdown(body, extras=['fenced-code-blocks'])
Then in the template body post is called:
{{ body_md|safe }}
That works correctly. However I'm trying to pass the body text to a javascript function that splits the text in two columns and renders it automatically in the html page respecting some boundaries. For example the text in both columns may have a width of 300px and a height of 800px.
The first problem I'm facing is that I can not render the text with javascript when using the markdown field. If I use :
<script type="text/javascript">
var html = "<div class='row'>" +
"<div class='content'> {{ body_md|safe }}</div>" +
"</div>";
document.write(html);
</script>
it doesn't work. However, if instead of using a text processed with markdown like {{ body_md|safe }}, I use something not processed, like the title, {{title}}. Then it renders correctly.
Any help is welcomed.
The problem you are having here is that safe
is causing Django to print body_md
(new lines and all) inside what you hoped would be Javascript.
So to be clear you are hope to get:
var html = "<div class='row'>" +
"<div class='content'><p>this is the first line</p>" +
"<p>this is the second line</p>" +
"</div>" +
"</div>";
but you're actually getting
var html = "<div class='row'>" +
"<div class='content'><p>this is the first line</p>
<p>this is the second line</p>
</div>" +
"</div>";
which isn't valid javascript. (tip, right click, view page source).
The easiest solution is to do:
<div id="hidden_body" style="display: none">{{ body_md|safe }}</div>
<script>
var hidden_body = document.getElementById("hidden_body").innerHTML;
var html = "<div class='row'>" +
"<div class='content'>" + hidden_body + "</div>" +
"</div>";
document.write(html);
By the way markdown2 is very slow, misaka is a great option instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.