How to import inside JavaScript files and using Django to load another js.
Statements like these don't work:
import { PolymerElement, html } from '{% static "#polymer/polymer/polymer-element.js" %}';
import '{% static "#polymer/app-layout/app-drawer/app-drawer.js" %}';
And also these too:
import { PolymerElement, html } from '#polymer/polymer/polymer-element.js';
import '#polymer/app-layout/app-drawer/app-drawer.js';
// myapp-shell.js
import `${static_path}`;
//....
<!DOCTYPE html>
<html lang="en">
<head>
{% load static %}
<script src="{% static 'node_modules/#webcomponents/webcomponentsjs/custom-elements-es5-adapter.js' %}"></script>
<script src="{% static 'node_modules/#webcomponents/webcomponentsjs/webcomponents-loader.js' %}"></script>
<!-- Loading app-shell -->
<script>
var static_path = '{% static "my-icons.js" %}';
console.log(static_path);
</script>
<script type="module" src="{% static 'mycomponents/myapp-shell.js' %}"></script>
</head>
<body>
<myapp-shell></myapp-shell>
</body>
</html>
Is there is a way to do that without bundling the code in one big file, nor calling all files may be needed in the html file.
Thank you
It's definitely not right to use Django template tags inside your JS files, since they will not be processed by Django's template loader. I'd suggest either:
(a) Use only relative path imports in your JS files.
or
(b) Set up your Django STATICFILE_DIRS setting to include the node_modules directory and setting STATIC_ROOT to something like '/static'. Then do your module imports as import { x } from '/static/path/to/module'.
EDIT: Grammar
I searched that for a long time and the way I found to do that is:
inside your mains script use this function.
function include(file) {
var script = document.createElement('script');
script.src = file;
script.type = 'text/javascript';
script.defer = true;
document.getElementsByTagName('head').item(0).appendChild(script);
}
then load your script like this:
include('/static/js/your_js_file.js');
don't forget to register your static files directory in settings.py
example:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "your_folder of library"),
]
Mabe you can use a global variable at top of your js importations, because static it's only for django template, you can do something like this inside your template file:
<script>
var static_path = '{% static "#polymer/polymer/" %}';
</script>
end then import your js files using this path
import { PolymerElement, html } from `${static_path}/polymer-element.js" %}`;
Related
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
});
}
i set it up STATICFILES_DIRS STATIC_URL in settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'projectName', 'static'),
]
and i want to use javascript files in template but it is not working.
js file path is app/static/app/new.js
and i used it in template using this code
{% load static %}
<script type="text/javascript" src="{% static "app/new.js" %}">
$(document).ready(function(){
alert(1);
new_function();
});
</script>
function in new.js as well as alert does not working.
If I delete the src part in script tag, the alert works fine.
I can see the new.js script by accessing the path that appears in the chrome developer tool.
What did I do wrong?
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?
I AM getting the following error:
ReferenceError: Can't find variable: gettext
I have added the following in my urls.py:
js_info_dict = { 'domain': 'djangojs', 'packages': ('my_project_name',), }
urlpatterns += patterns('', (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict), )
I marked the string for localization as :
var lingualText = gettext("Are you sure you want to delete the photo?");
var statusConfirm = confirm(lingualText);
I have added the following line in my template:
<script type="text/javascript" src="{% url django.views.i18n.javascript_catalog %}"></script>
To generate the language file for the text inside javascript file, I use the following command:
python /usr/bin/django-admin.py makemessages -d djangojs -l de
I am able to generate the djangojs.po file for the desired language. And I also get all the strings marked in the JS file. When I see the output in Firebug, I see the above error i.e.:
ReferenceError: Can't find variable: gettext
Can anybody tell me where am I going wrong? Am I having the problem with the path for jsi18n ?
Thanks in advance.
getext() is provided by the {% url django.views.i18n.javascript_catalog %} script, so make sure it is included before your own code is, e.g.
<html>
<head>
<script type="text/javascript" src="{% url django.views.i18n.javascript_catalog %}"></script>
<!-- gettext() is now available -->
<script src="{{ STATIC_URL }}my_script_using_gettext.js"></script>
...
I'm in desperate need of help. I have followed many tutorials, as well as scrutinized this, this, this, and this article. I was getting error messages when following the Django documentation for static servers mentioned in the middle two articles, but I seem to be doing all the right things discussed in the two regarding settings.py, placing jquery.js in the correct directory and referencing the correct source in the actual html file.
My media directory seems to be being referenced - the css file in there is working splendidly, and if I go to http://127.0.0.1:8000/media/jquery.js, the jquery file is displayed.
Still, none of my functions that I've built after following multiple tutorials work for me on my django project. I've been banging my head against the wall for days - please help if you can.
Django App Project File:
__init__.py
data.db
javascript_app/
manage.py
media/
settings.py
templates/
urls.py
views.py
Javascript App Directory:
__init__.py
admin.py
models.py
tests.py
urls.py
views.py
Media Directory:
jquery.js
style_js.css
Templates Directory:
javascript_app/
base.html
note_list.html
In my main settings file:
import os.path
ROOT_PATH = os.path.dirname(__file__)
...
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), "media")
MEDIA_URL = 'http://127.0.0.1:8000/media/'
ADMIN_MEDIA_PREFIX = '/media/admin/'
In my main urls file:
from django.conf.urls.defaults import *
from django.views.static import *
from django.conf import settings
...
urlpatterns = patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }),
Desperately, I also put a media reference in my javascript_app 's urls.py (with the above-referenced import commands as well):
urlpatterns = patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }),
In templates/javascript/base.html:
<head>
<title>{% block title %}Notes Application{% endblock %}</title>
<link rel="stylesheet" href="/media/style_js.css">
<script type="text/javascript" src="/jennystanchak/media/jquery.js"></script>
</head>
And finally in templates/javascript/note_list.html:
{% extends "javascript/base.html" %}
{% block content %}
...
<script>
// my script here
</script>
{% endblock %}
What in the configuration am I missing??
Thank you SO MUCH in advance for your help :)
-- An aspiring female programmer
<script type="text/javascript" src="/jennystanchak/media/jquery.js"></script>
Shouldn't the path be src="/media/jquery.js" without /jennystanchak ?