Error while localizing Javascript content in Django - javascript

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>
...

Related

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)
}

Manage static link in js libraries within django

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
});
}

Django: How to import a javascript inside another javascript file

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" %}`;

JMSTwigJsBundle doesn't compile

In a search to optimize the possibility of my application made with symfony2, I choose the JMSTwigJsBundle to allow the usage of twig template both frontend or backend.
I use composer to install bundles and symfony (it is the 2.7.3 version)
I began to follow a tutorial who bring me to add both FOSJsRoutingBundle and JMSTwigJsBundle. The first one, installed first, work perfectly, but the second brought me different kinds of problem, beginning with "Uncaught ReferenceError: goog is not defined". I resolved it by adding the following content :
these two lines on app/autoloader.php as described in the official documentation ( http://jmsyst.com/bundles/JMSTwigJsBundle ):
$loader->add('JMS', __DIR__.'/../vendor/jms/twig-js-bundle');
$loader->add('TwigJs', __DIR__.'/../vendor/jms/twig-js/src');
The app/AppKernel.php is set with the following line :
new JMS\TwigJsBundle\JMSTwigJsBundle(),
I also add to my app/config.yml these lines :
Filters:
twig_js:
resource: "%kernel.root_dir%/../vendor/jms/twig-js-bundle/JMS/TwigJsbundle/Resources/config/services.xml"
apply_to: "\.twig$"
So, we can found inside my layout.html.twig the following lines
{% javascripts
'js/fos_js_routes.js'
'%kernel.root_dir%/../vendor/jms/twig-js/twig.js
'#NameSpaceNameBundle/Resources/views/customFolder/example.html.twig'%}
<script language="javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
And, thank to the filters on the config file, we don't need to add the filter line.
These modifications are from : https://github.com/schmittjoh/JMSTwigJsBundle/pull/13 post 3
I also do modifications presentend here : https://github.com/schmittjoh/twig.js/issues/35 post 2 :
I found a way to fix this issue by copyng the file
/Symfony/vendor/bundles/JMS/TwigJsBundle/Resources/config/services.xml
to
/Symfony/vendor/bundles/Symfony/Bundle/AsseticBundle/Resources/config/filters/twig_js.xml
and changing the service id from twig_js.assetic_filter to
assetic.filter.twig_js.
Every of theses modifications bring me to a new error :
Uncaught SyntaxError: Unexpected token %
on the created file "exemple.html.twig.js:1". For information, the twig file looks like :
{% twig_js name="example" %}
the html code
And the content generated on the new file is... exactly the same content than the twig's file.
So, please, what did I have to do to make it work ? Thank's
To make it work to and have a compiled version of any .twig, I had to include the "YUIcompressor" to the app/config/config.yml :
yui_css:
jar: "%kernel.root_dir%/Resources/java/yuicompressor.jar"
yui_js
jar: "%kernel.root_dir%/Resources/java/yuicompressor.jar"
and add the appropriate file to the associate path.
Then I add to the layout.html.twig
{% javascripts filter='?yui_js'
'js/fos_js_routes.js'
'%kernel.root_dir%/../vendor/jms/twig-js/twig.js
'#NameSpaceNameBundle/Resources/views/customFolder/example.html.twig'%}
<script language="javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
Finally I use the app/console assets:install and app/console assetic:dump to check if they're is nothing wrong, refreshed and it was ok (at least for me).

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