Python set value is undefined for JS - javascript

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>

Related

Referencing JavaScript file from a different assembly in a Blazor project

I have a Razor Class Library project in which I want to add a couple of custom components that use JavaScript interops. The interops work fine when I call functions that already exist in the Window object.
This, for example, works fine:
JSRuntime.InvokeVoidAsync("alert", "Hello world");
However when the functions I need are not native to the Window object, i.e. they are declared in a distinct interops.js file, I need to add a <script> tag referencing the said file in the page HTML. What is the path to that file since it resides in a different assembly?
There are two ways to approach this.
Consume static assets from a referenced RCL
From documentation
The files included in the wwwroot folder of the RCL are exposed to either the RCL or the consuming app under the prefix _content/{LIBRARY NAME}/. For example, a library named Razor.Class.Lib results in a path to static content at _content/Razor.Class.Lib/. When producing a NuGet package and the assembly name isn't the same as the package ID, use the package ID for {LIBRARY NAME}.
Read embedded asset contents using Reflection
This approach lets you execute Javascript code directly without need to include files in the HTML with <script>.
First create helper method to retrieve embedded javascript file contents:
public static string GetEmbeddedJSInteropCode(Assembly assembly, string path)
{
using var stream = assembly.GetManifestResourceStream(path);
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
Then you can call it like this
await JSRuntime.InvokeVoidAsync("eval", GetEmbeddedJSInteropCode(typeof(SomeRCLType).Assembly, "SomeRCL.SomeFolder.Init.js"));
await JSRuntime.InvokeVoidAsync("someRCLFunction", "Foobar");
When the Razor Class Assembly is referenced in a Blazor Web Assembly project, the content of the Razor wwwroot/ folder is copied in the Blazor _content/*namespace*/ folder. So the solution is to move the .js file in the wwwroot/ and reference it in the script tag like this:
<script src="_content/*assembly_name*/file.js"></script>

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

Django URL Config for javascript files

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.

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