Manage static link in js libraries within django - javascript

So I was trying to add an audio recording function to my website developed with django.
I wanted to do something similar as https://github.com/addpipe/simple-web-audio-recorder-demo so I started by trying to run it without modification.
I took the same html as in the git linked above, put the js/ folder in my static/ folder, and simply changed the following lines (index.html, line 32-33)
<script src="js/WebAudioRecorder.min.js"></script>
<script src="js/app.js"></script>
for
{% load static %}
<script src={% static "js/WebAudioRecorder.min.js" %}></script>
<script src={% static "js/app.js" %}></script>
These js files load correctly, but the problem is that when I click record on my website, I get a "GET /myapp/record/js/WebAudioRecorderWav.min.js HTTP/1.1" 404 error in my django server.
WebAudioRecorderWav.min.js is called within WebAudioRecorder.min.js. I tried to use the {% load static %} trick in the js file, but it doesn’t work.
What would be the correct way to work around this?
Thanks in advance.

You should use the workerDir setting to set the correct path to the other imported js files. Probably your recorder is initialised in app.js, where you cannot use template tags like {% static %}. The best way is to create a global variable in your template before loading app.js:
In your HTML template:
<script>var jsFilesPath = "{% static 'js/' %}"</script>
<script src="{% static 'js/app.js' %}"></script>
In your app.js:
if (typeof jsFilesPath !== "undefined") {
audioRecorder = new WebAudioRecorder(sourceNode, {
workerDir: jsFilesPath // must end with slash
});
}

Related

Django3: dynamically generating js which I can use in HTML page

As we know in Django framework we can generate the HTML page based on some predefined template files.
Inside those templates we can use and some specific django keywords/operators/functions.
Like:
{% block stylesheets %}
<link href="{% static 'js/jquery/jquery-ui.css' %}" rel="stylesheet">
<link href="{% static 'vendor/chosen/chosen.css' %}" rel="stylesheet">
{% endblock stylesheets %}
But most important things which I want to touch in this question are related to tag 'translate'
"{% trans 'List of all available masters' %}"
So I can be sure that the final content of my page will use some predefined language.
And the places where I am using such tags are different: "simple" html content with / and etc tags AND inline javascripts blocks. Like:
<script type="text/javascript">
$('#datepicker_value').on('change', function(){
....
var dialog = BootstrapModalWrapperFactory.createModal({
title: '{% trans 'Extended information about the event' %}',
message: '<pre>'+JSON.stringify(info.event.extendedProps.description, null, 4)+'</pre>',
buttons: [
{
label: '{% trans 'Close' %}',
cssClass: "btn btn-secondary",
action: function (button, buttonData, originalEvent) {
return this.hide();
}
}
]
});
....
</script>
So my main question here is such:
HOW correctly I can move ALL <script>...</script> blocks from html template into the external JS file?
To keep all the functionality of the django framework working! And my 1 variant was - I should use the same technique which I use for generating HTMLs with Django framework abilities. But maybe in a little shorten variant: Right inside the views.py file - CAN I somehow correctly generate on the fly full content of GLOBAL.js file which will contains ALL ... blocks from html template - where they all were previously stored.
And in a such manner - that standard django template engine can convert all {% ..... %} placeholders in a correct real content BEFORE the full content of GLOBAL.js will be generated and given out. And especially the content of translatable placeholders!!! Well, then in the HTML page template I can insert a call to a special command that can display the contents of this script at the moment the page is rendered by the browser on the client side. Something like:
<script type="text/javascript" src="{% url 'GLOBAL.js' %}"></script>
Am i right? If yes - how I can do that step-by-step? Or maybe there is something new and more logical way?
Django version is the latest one!!! 3.*
P.S. Also I've faced with a problem of transferring script block with content like document.addEventListener('DOMContentLoaded', function(){...}); Looks like such event handlers can't be moved out to the separate JS file from HTML page((
There is no reason you couldn't use Django template tags inside Javascript files (or any other filetype for that matter). As an example, here's is a view that returns rendered Javascript:
from django.shortcuts import render
def render_javascript(request):
return render(request, 'myapp/global.js', {})
If you hook this view into your urlpatterns like this:
urlpatterns = [
path("js/global.js", render_javascript, name="globaljs"),
]
You can then use the {% url %} template tag to refer to it from your HTML templates like this:
<script type="text/javascript" src="{% url 'globaljs' %}"></script>
Now when your browser requests js/global.js, the Django view will take the template myapp/global.js, process it with the templating system, and return the rendered template.

Javascript queryselectors not reading classes and ID when used in Django project

When I am working outside Django file, everything works fine with javascript reading classes and Ids like
document.querySelector('.class_name').addEventListener
But when loaded in Django projects it gives an error that eventlistner can't read NULL.
{% comment %} css file for contacts.html {% endcomment %}
<script type="text/javascript" src="{% static 'info/js/for_recrs.js' %}"></script>
<link href="{% static 'info/css/for_recrs.css' %}" rel="stylesheet" type="text/css" />
{% endblock %}
Actually if you are declaring JS file in head, it will read it at that time itself without going through the HTML file. So, it reads null value of classes and ID.
To avoid that you can declare script file just beforeend of body.
OR
Use
window.onload = function() {
// do your stuff here.
}
It solved mine problem.

How to include a javascript from /js/ in jekyll

I've added the cookie consent code from here
It has
<script>
...
if(readCookie('cookie-notice-dismissed')=='true') {
{% include ga.js %}
{% include chatbutton.js %}
}
...
</script>
in the html. This is placed within _includes but I can't figure out how to include javascript like /js/foo.js, located in another directory. I believe this is bundled with bundler within the jekyll assets.
Up to now, I've added javascript on my layouts in the following way, but haven't used {% include %} for this yet and I don't know how to let the _includes/cookie_consent.html know ẁhere to find it.
<script src="/js/foo.js"></script>
<script>
$(function(){
new Foo(".js-foo");
});
</script>
I can see two options to solve this
you create a file in _includes that contains the links to the extra JS you want.
For example:
# /_includes/bar.html
<script src="/js/foo.js"><\/script>
Inside _cookie_consent.html you can then add{% include bar.html %}
You add the link directly to your body.
if(readCookie('cookie-notice-dismissed')=='true') {
const js = '<script src="/js/foo.js"></script>'
document.body.appendChild(js)
}

Django: How to keep JavaScript code separate in static folder when it uses a python variable

I have a bunch of canvases that needs to be rendered. I don't want put the
JavaScript code in a python loop, because I feel it's bad practice
home.html
{% load staticfiles %}
<head>
<script type="text/javascript" src="{% static
'canvas/canvasrender.js' %}"></script>
</head>
{% for canvas in user_canvas_set %}
<canvas class = "canvas" id="{{canvas.id}}" width="400" height="200"
canvas_post= ""{{canvas.canvas_post}}"" >
Your browser does not support the HTML5 canvas tag.</canvas>
**<script>
canvasrenderNP.canvaswrite("{{canvas.id}}","{{canvas.canvas_post}}")
</script>**
{% endfor %}
I made a custom function that returns an array of the users canvas ids, because I use the canvas id as the id for the canvas element.
home.html
<script>
alert("{{user_canvas_ids}}")
</script>
I get the desired output:
[247, 248, 251, 252]
Now when I put this in a static file
canvasrender.js
alert("{{user_canvas_ids}}")
then load it into
home.html
{% load staticfiles %}
<head>
<script type="text/javascript" src="{% static
'canvas/canvasrender.js' %}"></script>
</head>
output:
"{{user_canvas_ids}}"
I am confused to as what is going on. I thought that the script tag inserts the js file in between the "<script> </script>"
I know I can make a element like so and get the attribute, but I feel like that is not good practice, or is it fine?
<p id="canvas_ids" canvas_ids ="{{user_canvas_ids}}"> </p >
Is there anything else I can do so that I can avoid writing JavaScript code
in the HTML file?
Why this is not a duplicate question. It does not have anything about why the linked js file in the html page can not keep reference to the python variable. But if the JavaScript is coded in the html page it can
As you mentioned in your own comment, you can save user_canvas_id in a js variable in home.html and access it in your js file. Something like this:
<head>
<script>var user_canvas_id = "{{ user_canvas_id }}"</script>
<script type="text/javascript" src="{% static 'canvas/canvasrender.js' %}"></script>
</head>
I am confused to as what is going on. I thought that the script tag inserts the js file in between the "<script> </script>"
Kinda, but this is done client-side, by the browser who has no idea about the special meaning of curly braces in Django templates.
And static in the context of Django means just that: That Django serves that file as-is, without running it through the template engine. (Which wouldn't help here anyway, as for the JavaScript file in isolation, the value of user_canvas_ids would be unknown, so the template engine couldn't substitute anything useful for it.)

Jinja2 Parsing External JS Files

I currently use
<script type="text/javascript" src={% static 'app.js' %}></script>
to retrieve my JavaScript file.
However, app.js tries to use Jinja2 tags with are not translated when I import my script in this fashion.
An example, of a line causing an error in app.js would be
$('#tag').click(function() {
window.location.href = "{% url 'Project.views.views.viewname' %}";
});
How do I force {% url 'Project.views.views.viewname' %} to be translated to a url if it is located in an external JS file?

Categories

Resources