Rendering html using javascript and code from markdown and django - javascript

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.

Related

How to Prevent TD from ending up on a new line?

I am dynamically creating a table through Javascript and I DO want the table to continue off the right side of the page. Doing this manually lets the table continue off, but once I feed this into a for loop the <td>s wrap into a second line in the rendered HTML, creating two or more table rows when they reach the end of the page.
<div id="panelindex" style="overflow:scroll;text-align:center;">
<table border="0">
<tr></tr>
</table>
</div>
This is inside a table of its own (no style formatting). Then the Javascript:
var q = Math.floor((1/numpanels)*500);
if(q>50) q=50;
panelindex.innerHTML = "<table border='0'><tr>"
for(i=0; i<numpanels; i=i+1)
{
panelindex.innerHTML = panelindex.innerHTML + "<td><div id='panel" + i + "' onclick='jumppage(" + i + ")' style='float:left;text-align:center;margin:8px;border-width:3;border-color:white;border-style:none;'><a href='#" + i + "'><img src='thumbnails.php?image=blowem" + zeroFill(i,2) + ".gif&GIF&tw=128&th=128&quality=" + q + "'>\n" +
"<br />" + i + "</a></div></td>\n";
}
panelindex.innerHTML = panelindex.innerHTML + "</tr></table>"
You may notice that there is a <div> in the <td> and that is so I can apply a border marking the panel. Without the <div> it seems I cannot do that, and there are some other undesired effects. Any ideas what I can do so that all the <td>s end up on one line rather than split to a new line?
Example of what I want: http://edwardleuf.org/comics/jwb/009-conmet
What is happening: https://jsfiddle.net/w4uh0a3j/7/
Click the Show link.
innerHTML does not hold the string value you assign to it.
It parses the value as HTML, creates a DOM from it, inserts it into the document and then, when you read it back, it converts that DOM back into HTML.
This means that the string you assign is subject to error recovery and normalisation. In particular, the end tags you omitted are fixed.
panelindex.innerHTML = "<table border='0'><tr>"
console.log(panelindex.innerHTML);
<div id="panelindex" style="overflow:scroll;text-align:center;">
<table border="0"><tr>
</tr></table>
</div>
So when you start appending more data to it:
panelindex.innerHTML = panelindex.innerHTML + "<td>etc etc
You end up with:
<table border="0"><tbody><tr></tr></tbody></table><td>etc etc
Store your data in a regular variable. Only assign it to .innerHTML once you have the complete HTML finished.
A better approach then that would be to forget about trying to build HTML by mashing strings together (which is error prone, especially once you start dealing with characters that need escaping in HTML) and use DOM (createElement, appendChild, etc) instead.
OK,here is fixed html and js code. It seems like innerHTML fixes missing closing when updating html before all the code is building the rest of innerHTML. This code works :
<div id="panelindex" style="overflow:scroll;text-align:center;">
</div>
and js code :
var numpanels = 100;
var q = Math.floor((1/numpanels)*500);
if(q>50) q=50;
panelindex.innerHTML = "<table border='0'><tr>";
var html = "<table border='0'><tr>";
for(i=0; i<numpanels; i=i+1) {
html += "<td><div id='panel" + i + "' onclick='jumppage(" + i + ")' style='float:left;text-align:center;margin:8px;border-width:3;border-color:white;border-style:none;'><a href='#" + i + "'><img src='thumbnails.php?image=blowem" + ".gif&GIF&tw=128&th=128&quality=" + q + "'>\n" +
"<br />" + i + "</a></div></td>";
}
html += "</tr></table>";
document.getElementById("panelindex").innerHTML = html;

Dynamically add array contents as new elements - JQuery

edit: Problem solved! I was modifying the page before it was loaded so the script didn't actually do anything. I fixed it now and it works. Thanks for the help, I'll have to chalk this one up to being new to jQuery and it's weirdness.
Long story short I'm trying to make a webpage that dynamically takes Article titles, thumbnail images, descriptions, and links to them, and creates a nicely formatted list on the page. I'm trying to accomplish this in jQuery and HTML5.
Here is the sample data that I'll be using to dynamically populate the page. For now formatting isn't important as I can do that later after it works at all.
<script>
var newsTitles = ["If It Ain't Broke, Fix It Anyways"];
var newsPics = ["images/thumbnail_small.png"];
var newsDescs = ["August 14th 2015<br/><b>If It Ain't Broke</b><br/>Author: Gill Yurick<br/><br/> Sometimes, a solution isn't the only one. So how do we justify changes to systems that don't need to be fixed or changed? I explore various systems from other successful card games and how their approaches to issues (be they successes or failures in the eyes of the deisgners) can help us create EC."];
var newsLinks = ["it_aint_broke-gill_popson.html"];
var newsIndex = 0;
var newsMax = 1;
The section of code where I'm trying to use the contents of the arrays above to dynamically fill elements.
<td style="height:500px;width:480px;background-color:#FFF7D7;padding:20px" colspan=2 id="article">
<h1>Articles</h1>
<!-- the column for each news peice add an element with the thumbnail, the title and teh desc -->
<script>
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href="" newsLinks[i] + "">" + newsTitles[i] + "</h3>", "<img src=""newsPics[i] + "">","<p>" + newsDesc[i] + "</p>", ); $("div").append("hello");
}
</script>
<div id="articleList">
HELLO
</div>
</td>
Here is what it ends up looking like, I can post more info if needed as I am aware this may not be clear enough to fully explain my problem but I am unable to determine that. Thank you in advance.
try this
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href=""+ newsLinks[i] + "">" + newsTitles[i] + "</h3>, <img src=""+newsPics[i] + "">, <p>" + newsDescs[i] + "</p>" ); $("div").append("hello");
}
Concatation issue + typo for newsDescs
The following string is invalid html and is missing a +
"<h3 href="" newsLinks[i] + "">"
You need to use proper quotes for html attributes, not &quote;
Try
"<h3 href='" + newsLinks[i] + "'>"
OR
"<h3 href=\"" + newsLinks[i] + "\">" // `\` used to escape same type quote
Personally I prefer opening/closing html strings with single quotes but either will work
Note tht you should be getting a syntax error thrown in dev tools console which would have helped you locate problems
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href='" + newsLinks[i] + "'>" + newsTitles[i] + "</h3>");
$("#articleList").append("<img src='" + newsPics[i] + "'>","<p>" + newsDesc[i] + "</p>" );
}

Always there is one extra empty page when printing

I'm working on an application to print a page. There is ALWAYS a blank extra page. I tried those solutions listed here but the problem is still present.
My print function is as follows:
// divID1 = the base, big div
// divID2 = some iframe inside divID1 (a table)
// value = the title of the print page
function printDiv3(divID1,divID2,value)
{
var func = "<style>td,th {padding:10px}
html, body{color:#000; height: 90%}
h2{font-size:18px;}
h4{font-size:16px;text-align:center;margin-bottom:-40px}
input,select{background-color:#000;border:thin solid #999999;}
.footer{position:absolute;bottom:0px;left:0px;right:0px,text-align:center;
width:100%;font-size:12px;margin-bottom:0px}
.sign{float:right;text-align:right;direction:rtl}</style>";
var header = "<h4>" + value
+ "</h4><img align='right' width='150' src='images/logo.png'><br><br><br><br>";
var footer = "<div class='footer' align='center'>Tel. address, etc </div> ";
var sign = "";
//Get the HTML of div + uframe
var divElements = document.getElementById(divID1).innerHTML
+ "<div style='width:100%;height:900px;position:absolute;top:325px'>"
+ window[divID2].document.body.innerHTML + "</div>" ;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title></title>" + func + "</head><body>"
+ header +"<table border=1>" + divElements + "</table>"
+ sign + footer +"</body></html>";
//Print Page
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
window.close();
}
My page structure is as follows:
<div id="example" > <!-- base div -->
<table border='1' width="100%" class="imagetable" id="imagetable1" >
...
</table>
<!-- the iframe -->
<table border='0' width="100%" class="imagetable">
<tr><td><div>
<iframe id="iframe_form" src="S.php" frameborder=0 style="width:100%;height:400px" ></iframe>
</div></td></tr>
</table>
<table>
...
</table>
</div>
Is the cause of problem that the div contains three consequent table?
I think you shouldn't do like this. The better ay is convert your html content in pdf.
If you stay in html you should respect print format (as A4) to expect what it work...
If you don't mastered the content of iframe, take a javascript screenshot ^^:
Using HTML5/Canvas/JavaScript to take screenshots
I hope it help you.
See you.

HTML in JavaScript function basics

Ok, I'm having a huge problem, and I've been looking for days about how to do this. Either I can't read well enough to understand it, or I'm stupid. I'm not sure what it is yet. I'll be honest and say that this is homework, but I've been struggling with this for 3 days now, and as its an online class, I can't go see my instructor and ask him what I'm doing wrong. I have emailed him, but his help is limited and vague, and I cannot figure this out. Anyway, to the point. I want to add HTML to the text that's going to be displayed in a new window using a JavaScript function. Here's the basics of what I have.
function myWindow(){
var pageContent, pageTitle;
pageTitle = document.write("Selected Image Preview");
document.write.style.textAlign="center";
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)</script>";
pageContent += "<h3>"Name of Image"</h3>";
pageContent += "</head><body align="center"><strong>" + "<font color= " violet ">"Here is the image you selected. "</font>";
pageContent += "</strong></body></html>";
}
Now, I have no idea what I'm doing wrong, considering I've read almost everything that I could find, searched all over this site, as well as dozens of others. I've tried the W3 schools, and some site that looked like it was last updated in 2001, and my book has absolutely NO examples of HTML being used inside the function (it's a javascript book, so the HTML help is very limited). Starting at the top, it tells me that "Uncaught SyntaxError: Unexpected token ILLEGAL junk.html:16" on the script line. Then it won't load the rest of the page. If I comment that out, it tells me that '<h3>' is an unexpected identifier, and it just keeps going. There's always something wrong and if I comment out the lines that give errors, then there's nothing left. Please help me figure out what I'm doing wrong. And if it's necessary, I am calling the function onload with the <body onload="myWindow();"> tag.
P.S. Please don't kill me if I've formatted this incorrectly. I did read the directions, and tried to format this as neatly as possible.
The biggest problem was that the closing </script> tag in the line with the call to alert() terminated the script, even though it was within a string literal. See the link in my comment to your original post. There were some other problems with quotes, and if a teacher is really teaching the <font> tag in 2014, I think I should track him down and throw up in his lap.
Note that the slash in </script> and the embedded double-quotes are now escaped with backslashes. That's the biggest change. Also, the function now returns the computed value so it can be used.
This code goes through a JavaScript console clean. It doesn't open any new windows, and it doesn't deal with the "style" line, which I couldn't figure out.
function myWindow(){
var pageContent, pageTitle;
pageTitle = "Selected Image Preview";
// document.write.style.textAlign="center"; // WTF?
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)<\/script>";
pageContent += "</head>";
pageContent += "<body style=\"text-align: center;\">";
pageContent += "<h3>Name of Image</h3>";
pageContent += "<strong>" + "<font color= \" violet \">\"Here is the image you selected. \"</font>";
pageContent += "</strong></body></html>";
return(pageContent);
}
I've edited the code. The <h3> line was within the head of the document, now fixed, and I added a style attribute to <body> based on your remark about wanting text centered.
Ok, your code contains errors, because you need to learn how to work with strings and quotes and how to escape quotes.
var str1 = "qwe";
var str2 = "asd";
var str3 = str1 + str2; // will be qweasd
var str3 = str1 + '1111' + str2; // will be qwe1111asd
var str3 = str1 + 'z"1"' + str2; // will be qwez"1"asd
var str3 = str1 + "z\"1\"" + str2; // will be qwez"1"asd. There is no difference if you use double quotes or single. If you use single quotes, all single quotes in the string must be escaped with backslash and opposite with double quotes
// and the same with single quotes:
var str3 = str1 + 'z\'1\'' + str2; // will be qwez'1'asd
also, you are using document.write function, which overrides the content of current page, but you need a new window, which is why we should use function window.open which returns a new window handler. We save it into OpenWindow variable and then we apply our content using OpenWindow.document.write passing our string pageContent as a first parameter
and the correct code:
function myWindow(){
var pageContent, pageTitle;
document.title = "Selected Image Preview";
document.body.style.textAlign="center";
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)</script>";
pageContent += "<h3>Name of Image</h3>";
pageContent += '</head><body align="center"><strong><font color="violet">Here is the image you selected.</font>';
pageContent += "</strong></body></html>";
var OpenWindow = window.open('#','_blank','width=335,height=330,resizable=1');
OpenWindow.document.write(pageContent);
}
pageContent += "<h3>"Name of Image"</h3>";
You don't need quotes around name of image. The entire line should be treated as a String.
pageContent += "<h3>Name of Image</h3>";
Basically, anything in HTML tags doesn't need quotes unless you intend for quotes to appear.
For this line:
pageContent += "</head><body align="center"><strong>" + "<font color= " violet ">"Here is the image you selected. "</font>";
You should use single quotes.
pageContent += "</head><body align='center'><strong>" + "<font color='violet'>Here is the image you selected. </font>";
You should be able to fix the rest of your HTML, keeping in mind single quotes for attributer, no quotes for content.
As to the HTML itself, it should look like this to follow at least intended standards. You should move most of the styles eventually to CSS.
<html>
<head>
<title>Selected Image Preview</title>
<script>// your script here </script>
</head>
<body>
<div align='center'>
<!-- your content here -->
</div>
</body>

Display formatted raw html with jquery

I have a place where I am trying to show code in a text area. I have dumbed down the example but basically user can input some fields, click a button, and the code snippet displays in a text area below for them to edit if they want and then copy.
I finally got it working to display the actual code snippet. But now I can't seem to find a way to format it so that it is indented and looks nice.
var mySnippet =
"<div id=\"myOuterDiv\">"
+ "<div id=\"myInnerDiv\">"
+ "</div>"
+ "</div>";
$('#mySnippetArea').text(mySnippet);
Which displays in my text area like so.
<div id="myOuterDiv"><div id="myInnerDiv"></div></div>
Where as I would like to see it as:
<div id="myOuterDiv">
<div id="myInnerDiv">
</div>
</div>
I'd really like to avoid any 3rd party plugins as its for work an a pain to get approval. It's just 4 small snippets I need to format.
UPDATE
This appears to work as I need.
var mySnippet =
"<div id=\"myOuterDiv\">\r"
+ " <div id=\"myInnerDiv\">\r"
+ " </div>\r"
+ "</div>\r";
Output:
<div id="myOuterDiv">
<div id="myInnerDiv">
</div>
</div>
Add a \n if you want a new line like
var mySnippet = "<div id=\"myOuterDiv\">\n"
+ "<div id=\"myInnerDiv\">\n"
+ "</div>\n"
+ "</div>\n";
$('#mySnippetArea').text(eventSnippet);
Single character escape sequences:
\b: backspace (U+0008 BACKSPACE)
\f: form feed (U+000C FORM FEED)
\n: line feed (U+000A LINE FEED)
\r: carriage return (U+000D CARRIAGE RETURN)
\t: horizontal tab (U+0009 CHARACTER TABULATION)
\v: vertical tab (U+000B LINE TABULATION)
\0: null character (U+0000 NULL)
Example: http://jsfiddle.net/jtx7e/
just use <pre id="mySnippetArea"></pre> and add \n and space according to the needed layout
edit:
you can also write
var mySnippet =
"<div id=\"myOuterDiv\">\n\
<div id=\"myInnerDiv\">\n\
</div>\n\
</div>";

Categories