Changing image in Flask template through Javascript - javascript

So I have a flask app that has only one template (html file). The html file is changed through a javascript file. It changes the DOM through jquery and flask doesnt have a problem with this. However, when I'm changing a img tag it has trouble.
This is my javascript code.
$(document).ready(function(){
mainPage = $("#mainPage");
setMainPage();
});
function setMainPage(){
mainPage.html('<div><img src="{{ url_for('static',filename='images/facebook.png') }}" alt="icon" class="socialBtns"></div>');
}
this returns the error: "missing ) after argument list" and the error happens on the line number where I set mainPage.html(). So i thought it was the ' quotes that were causing the problem. so I escaped them using the backslash like this:
$(document).ready(function(){
mainPage = $("#mainPage");
setMainPage();
});
function setMainPage(){
mainPage.html('<div><img src="{{ url_for(\'static\',filename=\'images/facebook.png\') }}" alt="icon" class="socialBtns"></div>');
}
But when i do that all the text loads in just fine but the image spits out an error "http://127.0.0.1:5000/%7B%7B%20url_for('static',filename='images/facebook.png')%20%7D%7D 404 (NOT FOUND)"
So i tried setting this src url ({{ url_for(\'static\',filename=\'images/facebook.png\') }}) inside the html template to see if maybe i had a typo, and i don't. When it's loaded into the html template the image loads just fine. But for some reason when i try to change the DOM from my JS file it doesn't want to work. I've looked everywhere for a similar problem. but nobody seems to have this same issue. I even saw a blog post of someone changing the dom through ajax the exact same way and it worked fine. Please help.

Related

Why does the js function need to be inside the html file and cannot be separates in this case?

I currently have something like this
filename : notes.html
{% load staticfiles %}
<script src="{% static "bootstrap/js/Notes.js"%}"></script>
<div class="pure-container" data-effect="pure-effect-slide" style="height: 10px">
<label class="pure-toggle-label" for="pure-toggle-left" data-toggle-label="left" style="margin-top:50px">
<span class="pure-toggle-icon"></span>
</label>
</div>
Now I have a file called Notes.js which is like this (This file is being referenced in Notes.html file.)
Filename : Notes.js
$(".pure-toggle-label").click(function () {
console.log("Hello World");
})
Now from the above code when I click on pure-toggle-label I expect the console to get "Hello World". However seems like the click function never gets called. Now if I move the content of Notes.js to Notes.html surrounded by the tag <script> </script> then the function gets called. My question is why this is happening ? Why cant I separately place that function in a separate file and reference that file.Why does the function not get called when the function is moved to a separate js file
Things need to be taken care:-
1.Add a jquery library before any jQquery code (otherwise jQuery code will not executed).
2.Either put your script code at the end of the page or change it like below :-
$(document).ready(function(){
$(".pure-toggle-label").click(function () {
console.log("Hello World");
});
});
Js code (and jquery in your case ) will be executed as soon as the js interpreter find the snippets to execute... if the code to be executed is invoked before any js lib is loaded then you will get an "... not found error"... on the other hand most of initializing functions are anchored to the onload method in the site, this is because most jquery functions are related with dom elements that must be properly loaded before getting manipulated

Creating a custom dropzone

I'm using enyo's dropzone.js for image uploading functionality on a web site I'm in the process of creating. I want to initiate my own Dropzone object and override the previewTemplate and some of the event listeners and so on, but I'm a bit at a loss.
I have included dropzone.js and the js-file for my own customizations just before the closing HTML body tag as follows: (the funky format is Django template tags)
<script src="{% static 'js/dropzone.js' %}"></script>
<script src="{% static 'js/wm_dropzone.js' %}"></script>
and in my wm_dropzone.js I have the following for the time being:
var wm_dropzone;
wm_dropzone = Dropzone(document.getElementById("wm_dropzone"), {
url: "upload/",
});
I also have a div block higher up in the HTML defined as follows:
<div class="row">
<div class="col-xs-12" id="wm_dropzone">
</div>
</div>
This keeps giving me the following error in Firebug console:
TypeError: this.defaultOptions is undefined
dropzone.js (line 424, col 7)
Is there something I'm not doing quite right here? JavaScript world is still quite strange and unexplored to me, so I'm trying to poke my nose here and there and learn some in the process.
I've been trying to follow this tutorial right here and also the dropzone.js official docs, but I've been stuck at this point for quite some time :D
I'm not sure, but from the error, I guess that you are not using the 'new' keyword for a constructor.
Try using
var wm_dropzone = new Dropzone(document.getElementById("wm_dropzone"), {
url: "upload/",
});

src stripped from json html data when using angular.js and angular-sanitize.js

I'm an angular noob here... but enjoying figuring it out. I have simple json file containing text like so:
"gettingstarted":{
"title":"Getting Started",
"content":"<img ng-src='images/pageone-snorkeler.png' width='150' height='107' alt='Snorkeler' /><p>Getting Started...... and a lot of other html in here...</p>"
},"etc..."
I am trying to load images into the rendered html, however, angular seems to be stripping the src and ng-src from my html.
My page.tpl.html file looks like so:
<h1 ng-bind-html="page.title"></h1>
<div ng-bind-html="page.content"></div>
I am loading / using:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-route.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-sanitize.min.js"></script>
I can see all the html render in the page correctly from the json data, however, not the image. It is rendering like so:
<img width='150' height='107' alt='Snorkeler' />
What am I missing to get images to load in my html?
EDIT::::
Looks like I needed to word my question different... I found the answer here: ng-bind-html does not load image src
ng-bind-html-unsafe
...which isn't working for me... or use the fully resolved url: http://superraddomainname.com/image/image.png for example.
ng-bind-html-unsafe has been removed in angular 1.2. What you've done with ng-bind-html should work, you have to make sure you add ngSanitize as a dependency in your app. For example...
angular.module('myApp', ['ngSanitize']);
Demo - Fiddle

Underscore template in HTML generating mysterious 404 errors

Okay, I have this underscore template (simplified version), rendered from _template.html.erb, in my Rails app, somewhere on the page:
<script type="text/html" id="mytemplate">
<div class="foo">
<img src="{{= my_variable }}" />
</div>
</script>
Then I render it like this, elsewhere, when required:
// change it to mustache-style because of defaults clashing with erb
_.templateSettings = {
interpolate: /\{\{\=(.+?)\}\}/g,
evaluate: /\{\{(.+?)\}\}/g
};
options = {
my_variable: '/foo/bar/baz.img'
}
compiled = _.template($("#mytemplate").html());
$(compiled(options)).appendTo("#wherever");
This, in theory should work just fine and it does, except errors like this started popping up in server logs and elsewhere, browsers 404-ing on URLs like: http://example.com/{{=%20my_variable%20}}, or http://example.com/foo/{{=%20my_variable%20}}.
Now, my hunch is that it has something to do with the fact that it's an img tag and somehow the browser tries to GET it from the page, even though it's wrapped in script tags, but I have no idea why on earth. This is one of the recommended methods by many people for embedding underscore templates into HTML. And I can't attribute it to older browsers and/or robots either because server logs show these are real people using the latest Chrome etc.
Edit: after a bit more investigating, 1. it only happens to a few people (unique IPs) 2. all of them are using the latest version of Chrome. So maybe it's an extension gone haywire?
Any ideas?
You must change the type="text/html" to something non-existent like type="x-template" (or anything really)
This normally works if the cache is cleared and all.
If nothing really does it, then you could use external templates (files that you load). But if you want to keep them inline, then escape the problematics chars (with internal JS char encoding). This will be parsed the same by JS, but won't get caught by HTML parser.
You can use this tool: http://mothereff.in/js-escapes (uncheck the "only escape non-ASCII and unprintable ASCII characters" box)
That's what it could looks like:
<script type="text/html" id="mytemplate">
<div class="foo">
\x3Cimg src="{{= my_variable }}" />
</div>
</script>

Mustache JS Templating - How do I embed a variable in a script tag string?

I just started using Mustache and I like it so far, but this has me perplexed.
I am using the GitHub gist API to pull down my gists, and part of what I want to do is include the embedding functionality into my page. The problem is Mustache seems to not want to have anything to do with my dynamic script tag.
For example, this works fine:
<div class="gist-detail">
{{id}} <!-- This produces a valid Gist ID -->
</div>
Additionally, this works perfect:
<div class="gist-detail">
<script src='http://gist.github.com/1.js'></script> <!-- Produces the correct embed markup with Gist ID #1 -->
</div>
If I try to pull these together, something goes terribly wrong:
<div class="gist-detail">
<script src='http://gist.github.com/{{id}}.js'></script> <!-- Blows up! -->
</div>
Chrome Inspector shows this:
GET https://gist.github.com/%7B%7Bid%7D%7D.js 404 (Not Found)
... which looks like to me something is weird with escapes or whatnot, so I switch over to the raw syntax:
<div class="gist-detail">
<script src='http://gist.github.com/{{{id}}}.js'></script> <!-- Blows again! -->
</div>
And I get the same result in Inspector:
GET https://gist.github.com/%7B%7B%7Bid%7D%7D%7D.js 404 (Not Found)
How do I get the correct values to embed in the script tag?
EDIT
I am injecting the template as follows (in document.ready:
function LoadGists() {
var gistApi = "https://api.github.com/users/<myuser>/gists";
$.getJSON(gistApi, function (data) {
var html, template;
template = $('#mustache_gist').html();
html = Mustache.to_html(template, {gists: data}).replace(/^\s*/mg, '');
$('.gist').html(html);
});
}
The actually template is inside of a ruby partial, but it is wrapped in a div (not a script tag, is that a problem?) (that's hidden):
<div id="mustache_gist" style="display: none;">
{{#gists}}
<!-- see above -->
{{/gists}}
</div>
I assume a div is ok rather than a script because in either case, I'm pulling the .html(). Is this a bad assumption?
To avoid automatic escaping in Mustache use {{{token}}} instead of {{token}}.
It seems like your template is in HTML and trying to retrieve the template using html() results in a pre-URL-escaped template to be returned. Try placing your template inside a <script type="text/html"> tag instead.
When you embed your template inside an HTML element that excepts more HTML elements as children, it may get processed by the browser as HTML. Escaping may occur. By using a <script> tag with a non-script content type, you're basically telling the browser not to touch your template.
It looks like your script is getting requested before Mustache has a chance to update the src property. What you want to do is define the template in a way that it's not parsed as part of the DOM. A common approach is to define your template inside of a <textarea> tag. This will preserve formatting and prevent character escaping.
<textarea id="gist-detail-template" style="display:none">
<script src='http://gist.github.com/{{id}}.js'></script>
</textarea>
Now, to instantiate the template:
var template = $('#gist-detail-template').val();
var html = Mustache.to_html(template, yourTemplateData);
Here's an official example: http://mustache.github.com/#demo

Categories