Dynamic html is not getting rendered by jQuery.tmpl - javascript

I am using a jQuery template to render some dynamic data. A simplified version of what I am trying to do can be seen below:
var data = [{html:<i>html</i>}, {html:<b>html2</b>}];
var tmpl = $.tmpl(<div>${html}</div>, data);
$("#someContainer").html(tmpl);
I want to render HTML as HTML (HTML in bold) but somehow it renders as plain text (<.b>html<./b>). Can someone explain why?

try using the {{html}} marker:
var tmpl = $.tmpl('<div>{{html html}}</div>', data);
See docs here: html marker
_note: it's html html twice because your var is named that

Related

How do you insert HTML into a QuillJS?

Is it possible to insert raw HTML into a Quill? I've been searching the documentation but couldn't find anything.
If it's not possible, can I at least convert HTML into a Quill Delta?
The reason I need this is because I am grabbing the raw HTML of the text taken from Quill, so I can view it later in HTML style. Have I been doing everything wrong, and need to keep a Delta version of it as well?
On version 1.3.6,
You can use Quill.setContents(value) method.
And insert your new HTML like this:
const value = `<h1>New content here</h1>`
const delta = quill.clipboard.convert(value)
quill.setContents(delta, 'silent')
Quill documentation: https://quilljs.com/docs/api/#setcontents
I have found a way, looking extremely closely at the documentation. Method quill.clipboard.dangerouslyPasteHTML('raw html'); does the trick. https://quilljs.com/docs/modules/clipboard/#dangerouslypastehtml
Another way to insert HTML into Quill is by using vanilla JavaScript.
You can set your html to a variable, such as htmlToInsert.
Then target the contenteditable div created by Quill, by getting it by its class, ql-editor.
Finally, set the innerHTML of that div to the HTML you want to insert.
For example:
var htmlToInsert = "<p>here is some <strong>awesome</strong> text</p>"
var editor = document.getElementsByClassName('ql-editor')
editor[0].innerHTML = htmlToInsert
There is better way to do this:
const htmlMurkup = '<p>Good</p>'
let quill = new Quill()
quill.container.firstChild.innerHTML = htmlMurkup
I believe the most straight forward way is this:
quill.root.innerHTML = '<p>HTML Goes Here</p>'
You can also obtain the HTML from this property as well.
If you aren't getting the desired output. It could be because your html content is encoded.
Use this to convert it.
let realHTML = $('<textarea />').html("<p><strong>Hello</strong></p><p><br></p>").text();
console.log(realHTML);
This code will output
<p><strong>Hello</strong></p>
After this you can use this command to set the html content in quill editor
quill.root.innerHTML = realHTML;
or even this:
let initialContent = quill.clipboard.convert(realHTML);
quill.setContents(initialContent, 'silent');
Its proper your html is in the real html format before setting the value on quill. Else the html tags would be displayed verbally.
Just to add to #user1993629's answer, using quill.clipboard.dangerouslyPasteHtml(0, "raw html") will place the cursor at the end of the pasted content

Store Entire HTML page into jQuery Variable

I have an app that uses HTML Email templates. I want to write a script that parses through the HTML of an email template and modifies the code. This is easy when the template is loaded on the page, but I want to do these dynamically where the HTML is just a value from a <textarea> (or more specifically CodeMirror).
The value of the <textarea> (CodeMirror) would look like this:
<!doctype html>
<html>
<head>...HEAD HTML...</head>
<body>...BODY HTML...</body>
</html>
I've tried:
// This part works great. Stores the HTML as a varaible.
var template_html = codeMirrorInstance.getValue();
// This shows the proper HTML in console as text
console.log(template_html);
// From here I can't access the HTML though
console.log($(template_html).find('body'));
But I keep getting undefined. Nothing I try is working... any ideas?
It appears you can do what you are trying to do. You just have to create a new document and possibly an second instance of jQuery.
You should take a look at this: https://stackoverflow.com/a/15496537/1819684 and this: https://stackoverflow.com/a/15479402/1819684
$(function() {
var doctype = document.implementation.createDocumentType( 'html', '', '');
var dom = document.implementation.createDocument('', 'html', doctype);
var jq2 = jQuery(dom);
var txt = $('textarea').val();
console.log(jq2.find('html').html(txt).find('body'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>
<html>
<head>...HEAD HTML...</head>
<body>...BODY HTML...</body>
</html>
</textarea>

Use AJAX to update dynamic div with information read from a csv file (Python/Flask)

I need to update the contents of a dynamic div with information I a getting from a csv file using Python / Flask. I cannot attach my full code as it is quite long, but here is a summary of the problem.
I am using a normal csv read routine and then serving it with Flask:
#app.route('/myStuff', methods=['GET', 'POST'])
def myStuff():
with open('static/databases/myData.csv', 'rb') as n:
reader = csv.reader(n, delimiter=",")
counter = len(myDatabase)
myDatabase = list(reader)
myIds = [col[1] for col in myDatabase]
Then, in my myStuff.html I have a parent div to be fed:
<div id="myDiv"></div>
Later, I call the csv data like this:
var myDatabase = {{ myDatabase|safe }};
var counter = {{ counter|safe }};
Then, using javascript I generate a number of divs within myDiv according to the length of the csv data:
for(var i = 1; i < counter; i++) {
$('#myDiv').append('<div>' + myIds[i] + '</div>');
};
In parallel I have some routines to modify the csv file (specifically the number of items), and I want them to be updated wihout reloading the complete html. I have tried adding a button to my html:
<button type="button" id="myButton" >Reload</button>
And then using a simple function with jQuery to reload myDiv within the html:
$('#myButton').on('click', function() {
$('#myDiv').load('/myStuff.html');
});
But nothing seems to be reloading. I am quite new to this sort of routine, and I have not been able to find any tutorial or example dealing with the same kind of data (csv) using Python / Flask. Any help will be really appreciated.
Edit:
Thanks to #caisah I managed to reload the data using AJAX, but I am having a new problem. I only need the children of #myDiv to be reloaded and with the code I have for now the complete html is been reloaded within the #myDiv container:
$('#myButton').on('click', function() {
$('#myDiv').load('/myStuff');
});
I have tried pointing at the contents using:
$("#myDiv").load(location.href + " #myDiv");
After #Peca's answer to this question, but only the parent div (and not the children) gets reloaded. Any hints on how to achieve this?

process html string before insertion

I want to load some html from server, I store the loaded html in a string then I want to modify the values of certain tags and elements within that string before appending it :
here is how I'm trying to do it :
script of test1.html :
<head>....</head>
<body> <div id="main"></div></body>
<script>
$(document).ready(function(){
$.get("test2.html").done(function(data){
$("#rf", data).val("new value");
$("#main").append(data);
});
});
</script>
test2.html
<p id="rf"> <b>old value</b></p>
The first problem is trying to target the val() method of a paragraph. That will not do anything as it has no val property to return. You need to use text or html to replace the content.
Second, convert the HTML string to a DOM tree first with $(data) (see notes below as to why I use a dummy div and html() instead), then find the element, change it etc then append the new tree to the target:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/NWj62/1/
var html = '<p id="rf"> <b>old value</b></p>'
$(document).ready(function () {
var $html = $("<div>").html(html);
$html.find("#rf").html("new value");
$("#main").append($html);
//$.get("test2.html").done(function(data){
// $("#rf", data).val("new value");
// $("#main").append(data);
//});
});
You need to wrap the incoming HTML in a dummy div as find will not match the top element of the tree.
I substituted dummy data so you could see it working without the ajax call.
Note: $(htmlstring) will collapse html and body tags into a flatter structure than you might expect, but your example only has the paragraph so is fine.
Your code will be something like:
$(document).ready(function () {
$.get("test2.html").done(function(data){
var $html = $("<div>").html(data);
$html.find("#rf").html("new value");
$("#main").append($html);
});
});
You want some sort of template functionality, since getting HTML from server and transforming it into a DOM tree and then applying manipulations manually is a lot of code repetition for nothing. Also, it's relatively expensive to do dynamic tree manipalations.
Either the html is processed on the server or on the client side, is your choice.
Backend templates: depends on your backend framework (ie. Django has its own template module).
Fronted templates: You can use Underscore templates or Handlebars templates (more similar to Django templates).

appended html to the dom doesn't respect the charset

I have some HTML rendered by ajax, which works perfectly fine using the char-set utf-8 nevertheless some content it's appended to the dom by a JavaScript function using jquery. The problem is, the HTML rendered doesn't have the correct char-set.
Here's the example of the content added by JavaScript
var html = '<div class="right-item-container"><span style="font-size:24px;" class="item-friend-name">Mamá</span><br/><span class="clubName-container">school</span></div>';
$('.profile-container').empty().css({ 'padding-top' : '0'}).html(html);
It renders like this:
This works fine in a fiddle.
http://jsfiddle.net/HjCpp/
var html = '<div class="right-item-container"><span style="font-size:24px;" class="item-friend-name">Mamá</span><br/><span class="clubName-container">school</span></div>';
$('#test').html(html);
So it must be the way your original content is encoded.

Categories