Django URL Config for javascript files - javascript

Hey guys - I am having trouble setting up my Django urls file correctly for the following thing!
<script type="text/javascript" src="/javascript/HashMap.js"></script>
What happens is the file is attempted to get found : http://localhost/javascript/HashMap.js but this URL does not match any within the URL Config and therefore the GET request fails.
Can anyone lend a hand to help me find the correct line to add to allow this kind of thing to work!
Cheers
Andy

You need to serve your JavaScript as a static file.
How you do this in production depends on what Web server you're running with. Django doesn't normally serve up static files.
For example, for Apache, you'd put this in your Apache config:
Alias /javascript/ /usr/local/wsgi/static/javascript/
Then you can put your .js files in the directory referenced.
The Django docs have a entire page on just this topic (serving static files): http://docs.djangoproject.com/en/dev/howto/static-files/

Javascript is usually considered a static resource file. If that's true in your case, I would refer you to the Django documentation. If you really need to use urlconfs to point to a view that generates Javascript, then you will need to make an entry in your URLconf for it and point it to a view.

If you're trying to get only the file as static content, the problem will be surely at your MEDIA_ROOT and MEDIA_URL settings variables. Just check they're pointing to where the javascript file is and your MEDIA_URL should have a postfix to ensure that you're accessing an "special" directory where the media files are stored.
In the case you're trying to do some processing over the file, generating it at runtime, etc.
try with this regular expression:
r'^javascript/(?P<jsfile>.+\.js)$'
In your view declaration, instead of only get the request as parameter, you will have the request and a new param called jsfile, that is the filename you'requesting. So in the view, do the processing and return an HttpResponse object with the processed file contents.

Related

HTML src not correctly accessing required filepath

I have included a folder where I keep files I don't want people easily looking at, like passwords in php connection files. This folder is called 'inc' and is at the same level as the 'public_html' folder. I have put php files with database connection details in the 'inc' folder and accessed this using '../inc/' and the filename and it works perfectly - i.e.:
require_once('../inc/connection.php');
I would also like to put javascript files in the 'inc' directory and access them via the src path in HTML. I have tried the same approach as with the php file - that is using '../inc/' and the file name to access the files and for some reason it is not working:
<script src="../inc/moment.js"></script>
I have read similar queries to this on Stack Overflow and followed the right approach (locally and on server) but for whatever reason it is not accessing the js file. It does work however if I relocate the 'inc' folder to within the 'public_html' folder (for js files only) but this defeats the purpose of what I am trying to achieve - and in my mind should not work.
Does php treat the access of directories different to HTML's src hence different behaviour using '../'. I don't think it should and yet I can't get it to work.
Any help greatly appreciated!
A script tag with a source attribute is html that tells the browser to go get a file. Relative paths can be used, but your js files will need to be accessible to the public; they simply can't be hidden outside of the public root.
PHP is a scripting language running on your server. When it sees ../ in the proper contexts, such as the require_once directive you mention, it translates that into the proper path to the directory you are looking for, so it can look outside of the public directory.
Don't put sensitive items in the js, put them in protected files on the server. If you need the info at runtime, make an ajax call to access and use the data to provide the client with only the information it needs.

Python set value is undefined for JS

In my main python file, I have the following code.
#app.route('/accounts/test/learn/medium')
def medium():
word = random.choice(os.listdir("characters/"))
return render_template('accounts/test/medium.html', word=word)
My HTML Template "Medium" has a div called "character" which contains the word.
<div id="character" style="font-weight:bold;color:red" >{{ word }}</div>
My Javascript file, which I call body onLoad tries to set the png file for the word/character.
currentWord = document.getElementById("character").value
if(document.getElementById("characterPNG")!=null){
document.getElementById("characterPNG").src = "../../../style/images/characters/png/" +currentWord+ ".png";
When I run the application, Python sets the word in my HTML I can see that,
but JavaScript, can't see the value of character. It rather say's
Failed to load resource: the server responded with a status of http://path/undefined.png
Do you have any suggestions what might be wrong? Is it the sequence?
According to this answer Get content of a DIV using JavaScript you should use innerHTML instead of value:
currentWord = document.getElementById("character").innerHTML
As pointed out in the comments, I would make good use of url_for from Flask to generate urls for static files, as follows:
Quoting from Flask's doc:
Static Files
Dynamic web applications also need static files. That’s usually where
the CSS and JavaScript files are coming from. Ideally your web server
is configured to serve them for you, but during development Flask can
do that as well. Just create a folder called static in your package or
next to your module and it will be available at /static on the
application.
So, after you create a static folder, just reference it in your template with url_for method pointing out as well the filename:
<img id="characterPNG" src={{url_for('static', filename=word+'.png')}}></img>

How to write the content of external .js files in a js.haml file (Ruby on Rails)

I'm using Ruby on Rails framework and I love it.
Until now I was using the show.html.haml for my views and everything worked fine. We wanted to add another option of supporting a GET request which consists the post-fix .js. For this purpose we added to the controller another parallel view named show.js.haml.
The "magic" of Rails knows to route .html post-fix requests to the first and .js post-fix requests to the latter.
The problem is when a request gets routed to the show.js.haml view, I can't find a way to write the content of external .js files. All I get is the text itself (i.e. <script src="myscripts.js" type="text/javascript"></script>) but not the actual content of the file.
I've found a solution, which surely isn't optimal (performance, robustness etc): downloading the file to the server and use the following function:
!= File.open(Rails.root.join('public' , 'js', 'jquery-1.11.2.min.js'), 'rb').read
This is the only way I found to actually write the content of a .js file.
There must be a Ruby's elegant way to write the content of external .js files into a .js.haml file.
Any help would be appreciated here.
Thanks!
I'm not sure why you need this and which case this is a good idea for, but you can try this (untested):
# show.js.haml
// some javascript
= render file: Rails.root.join('public' , 'js', 'jquery-1.11.2.min.js')
// or
"#{render file: Rails.root.join('public' , 'js', 'jquery-1.11.2.min.js')}"
Of course this will only work for local resources accessible, but hey, that's what <script src= is for.
EDIT
In case of needing to store the contents of the file in a variable as a string, you can use capture. For remote files you can use open-uri, which is part of Ruby's stdlib.
# show.js.haml
- content = capture do
- render file: Rails.root.join('public' , 'js', 'jquery-1.11.2.min.js')
# for remote files
- content = open('http://url.to/file.js').read
You can print the content later on:
= content
I think what you need is the rails asset pipeline
http://guides.rubyonrails.org/asset_pipeline.html

How can I insert javascript source files into my pyramid python application and use them in my template?

I have redefined this question from the original a bit to make it more fundamental to the question at hand. The relevant parts of my filesystem are as follows.
env
tutorial
tutorial
templates
view.pt
static
myjava.js
views.py
__init__.py
Right now my view.pt template has
<script type="text/javascript" src="/static/myjava.js"></script>
Then in my __init__.py, I have
config.add_static_view(name='static',path='env/tutorial/tutorial/static')
And finally, the myjava.js file itself is very simple:
document.write("hello from the javascript file")
I am trying to follow this document: http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/assets.html
but right now none of the text is showing up. I feel like the problem lies in the paths i am giving it.
Some ideas I have had: in the config.add_static_view, the name='static' is confusing. I want users to be able to visit the url www.domain.com/firstpage, where firstpage is the result of a template that uses a javascript file resource (a file in the static folder). I am worried that these static assets are only for urls that start with www.domain.com/static/... Is this a valid concern? How can I tell the config.add_static_view function to serve the static resources for any views rendered from the view.pt template?
Edit: here is what worked:
in the template, use src="${request.static_url('tutorial:static/myjava.js')}"
then in the init.py use config.add_static_view(name='static',path='tutorial:static/')
Your javascript link, in the template, should be something like src="${request.static_url('tutorial:static/myjava.js')}"
This allows your application to be more easily relocated.
This also uses the appropriate asset specification, using the name of the package,
"tutorial", a colon, then a path relative to the location of the "tutorial" package, which in your case the package is at env/tutorial/tutorial.
Edited: I forgot about the Configurator object.
Here, you want to use a similar asset specification such as config.add_static_view('static', 'tutorial:static/').
You can make different static views for different directories as well, like: config.add_static_view('images', 'tutorial:images/')
When you do things like this, you can move the root of your application to another location, allowing you to have http://mysite.com/stable/ and http://mysite.com/devel/ having accesses to / be rewritten to /stable/.
The static views can be called from any template with code like ${request.static_url('tutorial:images/icons/favicon.ico')}
Was reading the docs here and it looks like when you call add_static_view it changes the path of the file? To quote the docs:
this means that you wish to serve the files that live in /var/www/static as sub-URLs of the /static URL prefix. Therefore, the file /var/www/static/foo.css will be returned when the user visits your application’s URL /static/foo.css.
In your case, since you're calling env/tutorial/tutorial/static "static", you might want to try src="static/Three.js"> instead

How to access proprietary .js file in Spring MVC?

I am newby in Spring, but have a task, and I am learning on the fly.
I used Roo to generates for me part of the code, but now I have to make some dynamic list binding, which is done with form, popping-up in new window, and when the submit button is pushed I have to insert the new values in the parent window.
For the purpose I wrote a .js file, which hooks the values to the parent DOM tree, but the point is that I can't configure Spring to deliver the required .js file to the browser.
The browser, doesn't recognize my function. Even when I try to access the .js file via the browser, I receive error that the file couldn't not be found.
I've tried to configure the web.xml, but it didn't work...
Any ideas, how I can configure the access to a .js file in a Spring MVC application?
Thanks a lot!
P.S. Respectively, I'll need to grant access for a static .htm(l) file... I suppose the principle for configuration of the access of static html files is the same..., right?
You just need to get the path to the file right. Assuming you have a Maven-like set-up (I assume you do because you're using Roo), then your script belongs under src/main/webapp - probably in something like a scripts folder.
Let's assume that your file is at src/main/webapp/scripts/myscript.js
You can create a URL reference for your script by adding the following Spring tag:
<spring:url value="/scripts/myscript.js" var="script_url"/>
This should give you the right path to your script, regardless of the context in which you later decide to publish your webapp.
After that, it's just a matter of using that reference:
<script type="text/javascript" src="${script_url}"></script>

Categories