This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 6 years ago.
Hey I've got the following problem:
I am building a little flask app, and usually i just stick with bootstrap and jinja templates to get what I want, but this time I needed a bit more customised version. In order to get a grip I started with a simple example of using custom js and flask to get the basic right. But lets go into detail:
Assume I have a simple flask web app called app.py located in my_app/ which looks like this
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(port=8080, debug=True)
and the corresponding index.html, which is located in my_app/templates, is simply
<!DOCTYPE html>
<html>
<body>
<p>Clicking here will make me dissapear</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$("p").click(function(event){
$(this).hide();
});
});
</script>
</body>
</html>
then I see the expected result, that is, i can click on the paragraph to make it disappear.
BUT: I would like to put the javascript part into a main.js file under static/js/. like so:
$(document).ready(function() {
$("p").click(function(event){
$(this).hide();
});
});
and the index.html becomes:
<!DOCTYPE html>
<html>
<body>
<p>Clicking here will make me dissapear</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src='/js/main.js'></script>
</body>
</html>
Unfortunately nothing will happen. I have tried other ways of referencing the script file as well but until now nothing works. I have the impression im missing something really simple. Thanks in advance!
Simply invoke the url_for function within the template, referencing the special static endpoint so that the correct url to the desired target resource be created. As the desired target is the main.js file inside static/js, this would lead to the following:
<script type=text/javascript src="{{
url_for('static', filename='js/main.js')
}}"></script>
The rest of the quickstart guide contains additional useful information.
Related
I am still a beginner in Javascript and I wondering if I can use innerHTML to post the whole HTML content from another page.
I have used innerHTML to just post an HTML code within the same .js page. For example:
I have main.js that contains this
class MyComponent extends HTMLElement {
connectedCallback() {
this.innerHTML = `<h1>Hello world</h1>`;
}
}
customElements.define('my-component', MyComponent);
and in the index.html I use this code to implement the main.js
<!doctype html>
<html lang="en">
<head>
<script type="application/javascript" src="js/main.js"></script>
</head>
<body>
<my-component></my-component>
</body>
</html>
The question is can I include an HTML page instead <h1>Hello world</h1> like header.html to get the whole HTML code from it? if not, Is there any way to do that?
Thanks.
Edit: I mean for example if I have a page named footer.html and in that page, I have an h1 ex. "Hello world" And I need to use the same h1 in another page index.html without rewrite it again. Can I make that h1 as a template to use in any other page using javascript?
My idea that I was looking for is:
Making main.js
get h1 from footer.html in main.js
import that script in index.html
using h1 in index.html
I know that I can do that using "include" in PHP but I am just trying to do it by javascript.
You can try:
document.body.innerHTML
to access page content.
You can do that with AJAX. Set an URL for that file and make a get request with AJAX.
Using JQUERY
$.get("file_path.html", function(fileText){});
The only related question I found for my issue is this one:
page fetched by AJAX cannot execute any javascript
But I don't want do use JQuery. I want to use vanilla javascript.
The problem is that I can't execute any javacript that is inside an html page that is fetched using the fetch api.
Here are my files:
index.html: This is the initial HTML page. It requests a file called index.js as an ES6 module
<!DOCTYPE html>
<html>
<head>
<script type="module" src="index.js"></script>
</head>
<body>
<main id="content" role="main"></main>
</body>
</html>
Then I have my index.js file:
import openTemplate from './shared-assets/js/openTemplate.js';
const target = document.getElementById('content');
openTemplate('dashboard.html', target);
This is the openTemplate.js file:
export default function openTemplate(templatePath, targetElement){
fetch(templatePath).then(response => {
response.text().then(html => targetElement.innerHTML = html);
});
}
And finally, the dashboard.html template that refuses to execute javascript:
<h1>Dashboard</h1>
<script type="module">
import myAlertFunction from 'myAlertFunction.js';
// this is just a function that encapsulates an alert call
// my real code will have much more complex functions being imported
myAlertFunction('test');
</script>
All this code should result in a scenario in which, when my index.html page loads, an alert should display with the text 'test', but this is not happening.
I want this to run on Firefox Quantum >= 66
What am I missing?
I'm using the built-in flask server and I want to show an animated pie chart, like here:
http://codepen.io/tpalmer/pen/jqlFG
or
http://jsfiddle.net/thmain/xL48ru9k/1/
For simplicity, I use the latter one.
The python flask server code is:
from flask import Flask, render_template, request, flash
from forms import ContactForm
app = Flask(__name__)
app.secret_key = 'blah'
#app.route('/', methods = ['GET', 'POST'])
def test():
return render_template('test.html')
if __name__ == '__main__':
app.run(debug = True)
I did copy the javascript code provided on the webpage to the file static/script2.js
and the css code to static/css/style_d3.css
My HTML code is
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="//style_d3.css" type="text/css">
</head>
<body>
<p>test</p>
<div class="animated-ring">
<svg></svg>
</div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="//script2.js"></script>
</body>
</html>
I run the webpage through the flask server. But I get a webpage that just says "test", there's no chart.
What do I do wrong?
I'd really appreciate if someone could help me.
You only render the test.html at "/" path, the script2.js needs to be rendered too at "/script2.js".
Try this one liner at your project's root directory to host all files:
python -m SimpleHTTPServer
I think you need to set to a path your js file. In your app dir create a static folder then put your script2.js file and when you call this file at html use flask url_for() function
src="{{url_for('static', filename='script2.js'}}"
Is it possible (and a good idea) to pass dynamic data to a JavaScript include file via a hash url?
Such as:
<head> <script src="scripts.js#x=123&y=456"></script> </head>
I am looking for an alternative to inline js in dynamically built pages:
<head>
<script src="scripts.js#x=123&y=456"></script>
<script>
$( document ).ready(function() {
pageInit(123, 456)
});
</script>
</head>
Is it a good idea to avoid inline js? How can you pass dynamic data without ajax which creates a needless roundtrip network request?
Note: The hash bang url is a special because the browsers ignore the hash portion of the url when checking the cache. At least for html files.
So all of these will reuse the index.html file it is in the cache:
index.html
index.html#x=123
index.html#x=345345
index.html#x=2342&y=35435
This same principle should hold true for javascript files. What I hope to achieve is to reuse the cache version of script.js from page to page.
Going to index.php, include this:
<head> <script src="scripts.js#x=123&y=456"></script> </head>
Then going to fun.php include this
<head> <script src="scripts.js#x=898756465&y=5678665468456"></script> </head>
Then going to see.php include this
<head> <script src="scripts.js#session=887987979&csrf_token=87965468796"></script> </head>
From page view to page view, pass whatever info the page needs via the hash bang while at the same time reuse scirpt.js from cache.
So, is it possible to read the hash bang info from within the scirpts.js?
If the HTML file you are creating is dynamic, then just create inline JavaScript. Writing an include will just create an extra request from the browser, which you can avoid in the first place.
Edit:
just include a JavaScript file that reads the URL, you don't need to pass any variables (but of course, you also could):
$(document).ready(function() {
// pseudo code
hashbang = location.href.substr(location.href.indexOf('#') + 1);
if (hashbang.x && hashbang.y) {
pageInit(hashbang.x, hashbang.y);
} else if (hashbang.csrf_token) {
// do something else
}
});
I have been building my first ASP.NET MVC web app. I have been using the jQuery autocomplete widget in a number of places like this:
<head>
$("#model").autocomplete({ source: '<%= Url.Action("Model", "AutoComplete") %>' });
</head>
The thing is I have this jQuery code in a number of different places through my web app. So i thought I would create a seperate javascript script (script.js) where I could put this code and then just include it in the master page. Then i can put all these repeated pieces of code in that script and just call them where I need too. So I did this. My code is shown below:
In the site.js script I put this function:
function doAutoComplete() {
$("#model").autocomplete({ source: '<%= Url.Action("Model", "AutoComplete") %>' });
}
On the page I have:
<head>
<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/site.js" type="text/javascript"></script>
<script type="text/javascript">
doAutoComplete();
</script>
</head>
But when I do this I get an Invalid Argument exception and the autocomplete doesnt work. What am I doing wrong? Any ideas?Do i need to pass something to the doAutoComplete function?
The <%= will not be evaluated in your external javascript.
Solution: pass the URL as a parameter to your javascript function.
<script>
doAutoComplete('<%= Url.Action("Model", "AutoComplete") %>');
</script>
function doAutoComplete(url) {
$("#model").autocomplete({ source: url });
}
You need to put the function call in a script block, and make sure jquery is loaded before your site.js ...
<head>
<script src='path/to/jquery.js'></script>
<script src="../../Scripts/site.js" type="text/javascript"></script>
<script>
doAutoComplete();
</script>
</head>
EDIT:
Maybe the '<%= ... =%>' tag isn't being evaluated server-side, before the function gets sent to the browser? Here is an article on this: http://www.west-wind.com/weblog/posts/252178.aspx
Here is a quote from the post:
There's also a problem if you need
access to the [ASP.NET] variables in
.js files - you can't embed script
tags into a .js file so getting a
dynamic value into a static file is
problematic