I read and followed the instructions in here, but can't seem to see the string in the javascript in the po file.
structure of my project is:
cb/
cb_app
cb
static_files
templates
First I copied these into my url.py:
js_info_dict = {
'packages': ('cb_app',),
}
urlpatterns = patterns('',
(r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
)
Then I added this script to my html:
<script type="text/javascript" src="{% url django.views.i18n.javascript_catalog %}"></script>
The actual script where I would like to get the translation, is as simple as that:
$(document).ready(function () {
$('#id_sales_item').chosen({no_results_text: gettext('No results match')});
});
...and is utilized in the same html.
So is there anything more I need to do?
All I did then was to run the line below both from cb/cb and from cb/cb_app.
django-admin.py makemessages -l en_GB
But still no sign of 'No results match' in either cb/cb/locale nor in cb/cb_app/locale
Any tips?
I have finally found the problem.
The documentation suggests creating the messages once from the Django project and once from Django app. That way you end up with two locale directory. And in neither of those would the javascript translations be picked up anyway. This is quite a mess.
The cleanest solution I have found is to go to settings.py and insert this line (see also my project hierarchy above):
LOCALE_PATHS = ( '/home/kave/projects/cb/locale',)
Then create a directory called locale in the project-root-directory (see the path above)
Don't forget applying the entries into url.py and html as well (see above).
Finally now that the local's are unified into one place, go to project-root-directory: /home/kave/projects/cb and run these two commands:
django-admin.py makemessages -l en_GB
django-admin.py makemessages -d djangojs -l en_GB
The first command get the translation texts from both project and app subfolders.
The second gets the javascript translation into a second po file.
Thats it.
Related
I am making a pot file where I want the file to scan for gettext keywords in a JS jQuery file. It scans the php perfectly, but the .js file seems not be working. I am wondering if I have actually the extractor setup correct for the command's language. This is what I have:
Language: JS
List of extensions: *.js
Command: xgettext --language=C --force-po -o %o %C %K %F
It scans the file, but nothing is added. What is the language for jQuery?
To give more information:
This is an example of the JS file:
jQuery(document).ready(function() {
if(location.href.indexOf('/<?php esc_html_e('url_page_discount', 'custom-translation-strings' ?>/') > -1){ //rewards
jQuery('.rs_custom_fblike_button').attr('value', '<?php esc_attr_e('I Like', 'custom-translation-strings' ?>');
if (jQuery('#menu-item-10159').length){
jQuery('#rs_friend_subject').attr('value', '<?php esc_attr_e('Discount for an interesting store!', 'custom-translation-strings' ?>');
}
}
});
I have covered the esc_attr_e() in the sources keywords:
I am wondering if I have actually the extractor setup correct for the command's language
You don't. The very fact that you're even configuring extraction suggests that you're either using a very old version of Poedit or you're adding custom configurations. In either case, don't: update to the latest, delete or disable all your custom extractors, and let Poedit do its thing with defaults.
Command: xgettext —language=C --force-po -o %o %C %K %F
You're asking Poedit to treat JavaScript files as being written in C. The results predictably follow the GIGO principle.
This is an example of the JS file:
You're putting (even PHP!) code into string literals. That's a) not going to work and b) cannot have any translatable strings extracted from.
I have a hybrid AngularJS/Angular application that will take some time to complete migration to fully be an Angular app. While this process occurs, I'd like to move away from the previous build system to using the CLI and webpack to manage all of the old AngularJS scripts as well. This is possible as I've done it before by adding all of my scripts to the scripts section in angular.json like the following:
"scripts": [
"src/app/angularjs/app.js",
"src/app/angularjs/controllers/main.js",
"src/app/angularjs/services/someService.js",
"src/app/angularjs/controllers/someController.js"
],
This works well and the CLI builds via ng serve and ng build continue to work for the hybrid bootstrapped app as needed. The problem I'm running into now is manually listing each file for the current application I'm migrating is not ideal. I have hundreds of scripts that need to be added, and what I need is to be able to use a globbing pattern like the following:
"scripts": [
"src/app/angularjs/**/*.js"
],
The problem is this syntax from what I can tell is not supported. The glob pattern is supported in the assets section of angular.json as stated here but not in the scripts section: https://angular.io/guide/workspace-config#assets-configuration
In the scripts section I can't find a similar solution. It does have an expanded object API, but nothing that solves the problem I can tell to select all .js files from a particular directory as listed here: https://angular.io/guide/workspace-config#styles-and-scripts-configuration
Is it possible by some means to use a glob pattern or similar approach to select all files of a directory for the scripts section in angular.json so I don't have to manually list out hundreds of individual .js files?
The Bad News
The scripts section does not support the same glob patterns that the assets section does.
The Good News(?)
Since you're transitioning away from AngularJS, you hopefully won't have any new files to import in the future, so you could just generate the list of all the files you need to import.
Make your way to the src/app/angular directory and run the following:
find . -iregex '.*\.\(js\)' -printf '"%p",\n'
That will give you your list, already quoted for your convenience. You may need to do a quick search/replace (changing "." to "src/app/angularjs"), and don't forget to remove the last comma, but once you've done that once you should be all set.
The Extra News
You can further filter out unwanted files with -not, so (per your comment) you might do:
find . -iregex '^.*\.js$' -not -iregex '^.*_test\.js$' -printf '"%p",\n'
And that should give you all your .js files without your _test.js files.
KISS
Of course, this isn't a complex pattern, so as #atconway points out below, this will work just as well:
find . -iname "*.js" -not -iname "*_test.js" -printf '"%p",\n'
I'll keep the above, though, for use in situations where the full power of regex might come in handy.
I wanted to extend an anser of #JasonVerber and here is a Node.JS code and therefore (I believe) cross-platform.
Firstly install find package and then save contents from the snippet in some file.js.
Afterwards, specify paths so that they resolve to where you wan't to get your files from and where to put the resulting file to.
After that node file-name.js and this will save all found file paths to the resultPath in result.txt ready to Ctrl+A, Ctrl+C, Ctrl+V.
const find = require('find');
const path = require('path');
const fs = require('fs');
// BEFORE USAGE INSTALL `find` package
// Path to the folder where to look for files
const sourcePath = path.resolve(path.join(__dirname, 'cordova-app', 'src'));
// Path that will be removed from absolute path to files
const pathToRemove = path.resolve(path.join(__dirname, 'cordova-app'));
// Path where to put result.txt
const resultPath = path.resolve(path.join(__dirname, './result.txt'));
// Collects the file paths
const res = [];
// Path with replaced \ onto /
const pathToRemovehReplaced = pathToRemove.replace(/\\/g, '/');
// Get all fils that match a regex
find.eachfile(/\.js$/, sourcePath, file => {
// First remove all \ with / and then remove the path from root to source so that only relative path is left
const fileReplaced = file.replace(/\\/g, '/').replace(`${pathToRemovehReplaced}/`, '');
// Surround with quoutes
res.push(`"${fileReplaced}"`);
}).end(() => {
// Write file and concatenate results with newline and commas
fs.writeFileSync(resultPath, res.join(',\r\n'), 'utf8');
console.log('DONE!');
});
The result I got while testing (/\.ts$/ for regex)
"src/app/app.component.spec.ts",
"src/app/app.component.ts",
"src/app/app.module.ts",
"src/environments/environment.prod.ts",
"src/environments/environment.ts",
"src/main.ts",
"src/polyfills.ts",
"src/test.ts"
I have a really simple website (ASP.NET core) that is a single .html static page and 6 .js files.
In one of the js files are some data that is based on my configuration:
localhost
dev
production
right now, it's hardcoded for my localhost.
Is there way that I can build/package the simple app so that if i say dev or prod in some command line arg, it replaces those values with something from somewhere else?
eg.
in main.js:
var environment = "localhost";
var rooturl = "https://localhost:43210";
and lets imagine i wish to build to my dev server...
var environment = "dev";
var rooturl = "https://pewpew.azurewebsites.com";
Is this possible? To keep things simple, assume I know nothing of JS tools and processes. (it's actually the truth, but lets not tell anyone that).
Update (further clarifications):
with 1x static html file and 6x static JS files, I have a static website. So i'm hoping to generate the js files as static files (still) but with the environment data already compiled in it.
you can use some build tools like grunt. where you can define build task which takes the environment parameter and change the variables to the desired values.
another (more simple) way is to dynamicaly create main.js (with dependency on the environment) file with your backend and the frontend will load it when it starts. src of the script tag can be the asp script, where the output is javascript
This is a snippet from a project in which I do just that. I replace various place holders with values stored in the environment variables.
This example is based on a linux environment, so I used sed to modify the file in-place, however you could just as easily read the file into memory, do the replace and write it back to disk.
grunt.task.registerTask('secretkeys', 'Replace various keys', function() {
var oauth;
try{
oauth = JSON.parse(process.env.oauthKeys).oauth;
}
catch(e){
oauth = {google:{}};
}
var replaces = {
'==GOOGLECLIENTID==':oauth.google.client_id || '{**GOOGLECLIENTID**}',
'==GOOGLESECRETKEY==':oauth.google.client_secret || '{**GOOGLESECRETKEY**}',
'==SECRETKEY==':oauth.secret || '{**SECRETKEY**}',
'==LOCALAUTH==':oauth.login,
};
const child = require('child_process');
grunt.file.expand('bin/**/*.json').forEach(function(file) {
grunt.log.write(`${file} \n`);
for(var key in replaces){
var cmd = 'sed -i s~{{orig}}~{{new}}~g {{file}}'
.replace(/{{file}}/g,file)
.replace(/{{orig}}/g,key.replace(/~/g,'\\~'))
.replace(/{{new}}/g,replaces[key].replace(/~/g,'\\~'))
;
grunt.log.write(` - ${key} \n`);
//grunt.log.write(` ${cmd} \n`);
child.execSync(cmd);
}
});
});
Hopefully you can modify to your purposes.
EDIT : I am reconsidering my answer, you are modifying javascript on a windows environment. You are likely better using PowerShell
(gc script.js) `
.replace("==GOOGLECLIENTID==",$Env:GoogleClientId) `
.replace("==SECRETKEY==",$Env:SecretKey) `
> script-build.js
So after re-reading your question, I realize there is a better solution that I have used in the past. My other answer is still relevant, so I'll leave it.
It may be simplest to just create a config file in the same folder.
<html>
<head>
<script type="text/javascript" src="config.js" ></script>
<script type="text/javascript" src="myscript.js" ></script>
</head>
<body>
ask me your questions, bridgekeeper
</body>
</html>
config.js
var config = {
'colour': 'yellow'
};
myscript.js
var user = prompt("What is your favourite colour?", "");
if(user !== config.colour){
alert("No BLUE! Ahhh....");
}
else{
alert("You may pass");
}
This is the technique I use when developing simple HTA apps for use around the office.
Check out envify. You can run it from the command line. https://github.com/hughsk/envify
sudo npm install -g envify
Say you have
var myVar = process.env.MYVAR;
Run from the command line
MYVAR=somevalue envify input.js > output.js
and the output js file should have
var myVar = 'somevalue';
I'm using requireJS to load scripts. It has this detail in the docs:
The path that is used for a module name should not include the .js
extension, since the path mapping could be for a directory.
In my app, I map all of my script files in a config path, because they're dynamically generated at runtime (my scripts start life as things like order.js but become things like order.min.b25a571965d02d9c54871b7636ca1c5e.js (this is a hash of the file contents, for cachebusting purposes).
In some cases, require will add a second .js extension to the end of these paths. Although I generate the dynamic paths on the server side and then populate the config path, I have to then write some extra javascript code to remove the .js extension from the problematic files.
Reading the requireJS docs, I really don't understand why you'd ever want the path mapping to be used for a directory. Does this mean it's possible to somehow load an entire directory's worth of files in one call? I don't get it.
Does anybody know if it's possible to just force require to stop adding .js to file paths so I don't have to hack around it?
thanks.
UPDATE: added some code samples as requested.
This is inside my HTML file (it's a Scala project so we can't write these variables directly into a .js file):
foo.js.modules = {
order : '#Static("javascripts/order.min.js")',
reqwest : 'http://5.foo.appspot.com/js/libs/reqwest',
bean : 'http://4.foo.appspot.com/js/libs/bean.min',
detect : 'order!http://4.foo.appspot.com/js/detect/detect.js',
images : 'order!http://4.foo.appspot.com/js/detect/images.js',
basicTemplate : '#Static("javascripts/libs/basicTemplate.min.js")',
trailExpander : '#Static("javascripts/libs/trailExpander.min.js")',
fetchDiscussion : '#Static("javascripts/libs/fetchDiscussion.min.js")'
mostPopular : '#Static("javascripts/libs/mostPopular.min.js")'
};
Then inside my main.js:
requirejs.config({
paths: foo.js.modules
});
require([foo.js.modules.detect, foo.js.modules.images, "bean"],
function(detect, images, bean) {
// do stuff
});
In the example above, I have to use the string "bean" (which refers to the require path) rather than my direct object (like the others use foo.js.modules.bar) otherwise I get the extra .js appended.
Hope this makes sense.
If you don't feel like adding a dependency on noext, you can also just append a dummy query string to the path to prevent the .js extension from being appended, as in:
require.config({
paths: {
'signalr-hubs': '/signalr/hubs?noext'
}
});
This is what the noext plugin does.
requirejs' noext plugin:
Load scripts without appending ".js" extension, useful for dynamic scripts...
Documentation
check the examples folder. All the info you probably need will be inside comments or on the example code itself.
Basic usage
Put the plugins inside the baseUrl folder (usually same folder as the main.js file) or create an alias to the plugin location:
require.config({
paths : {
//create alias to plugins (not needed if plugins are on the baseUrl)
async: 'lib/require/async',
font: 'lib/require/font',
goog: 'lib/require/goog',
image: 'lib/require/image',
json: 'lib/require/json',
noext: 'lib/require/noext',
mdown: 'lib/require/mdown',
propertyParser : 'lib/require/propertyParser',
markdownConverter : 'lib/Markdown.Converter'
}
});
//use plugins as if they were at baseUrl
define([
'image!awsum.jpg',
'json!data/foo.json',
'noext!js/bar.php',
'mdown!data/lorem_ipsum.md',
'async!http://maps.google.com/maps/api/js?sensor=false',
'goog!visualization,1,packages:[corechart,geochart]',
'goog!search,1',
'font!google,families:[Tangerine,Cantarell]'
], function(awsum, foo, bar, loremIpsum){
//all dependencies are loaded (including gmaps and other google apis)
}
);
I am using requirejs server side with node.js. The noext plugin does not work for me. I suspect this is because it tries to add ?noext to a url and we have filenames instead of urls serverside.
I need to name my files .njs or .model to separate them from static .js files. Hopefully the author will update requirejs to not force automatic .js file extension conventions on the users.
Meanwhile here is a quick patch to disable this behavior.
To apply this patch (against version 2.1.15 of node_modules/requirejs/bin/r.js) :
Save in a file called disableAutoExt.diff or whatever and open a terminal
cd path/to/node_modules/
patch -p1 < path/to/disableAutoExt.diff
add disableAutoExt: true, to your requirejs.config: requirejs.config({disableAutoExt: true,});
Now we can do require(["test/index.njs", ...] ... and get back to work.
Save this patch in disableAutoExt.diff :
--- mod/node_modules/requirejs/bin/r.js 2014-09-07 20:54:07.000000000 -0400
+++ node_modules/requirejs/bin/r.js 2014-12-11 09:33:21.000000000 -0500
## -1884,6 +1884,10 ##
//Delegates to req.load. Broken out as a separate function to
//allow overriding in the optimizer.
load: function (id, url) {
+ if (config.disableAutoExt && url.match(/\..*\.js$/)) {
+ url = url.replace(/\.js$/, '');
+ }
+
req.load(context, id, url);
},
The patch simply adds the following around line 1887 to node_modules/requirejs/bin/r.js:
if (config.disableAutoExt && url.match(/\..*\.js$/)) {
url = url.replace(/\.js$/, '');
}
UPDATE: Improved patch by moving url change deeper in the code so it no longer causes a hang after calling undef on a module. Needed undef because:
To disable caching of modules when developing with node.js add this to your main app file:
requirejs.onResourceLoad = function(context, map)
{
requirejs.undef(map.name);
};
I would like be able to run a single command in my project folder to concatenate and compress all of my javascript files (perhaps with YUI Compressor) into a single output file.
If possible I would like to partially specify the order in which they are concatenated together but not have to keep track of every single javascript file. Perhaps a config file could be built which looks like this:
application.js
excanvas.js
json2.js
jquery*.js
flot/*
backbone*.js
app/screen-*.js
app/main.js
app/crud-*.js
app/*
*
Does anyone know of either an existing tool to do something like this, could whip together a bash/ruby/node/perl script, or even a better methodology? I'm building a Single Page App with heavy JS usage (~40 files) to be consumed by people with low bandwidth.
I would need the solution to be executable on my OS X development machine.
find . -iname "*.js" -exec cat "{}" \; > singlefile.js
[JS compressor] singlefile.js
First concatenate the files, then compress them.
If you really care, though, you may want a real JS optimizer like the RequireJS optimizer.
given a folder of javascript files:
geee: ~/src/bash/js-files
$ find .
.
./application.js
./jquery-ui.js
./all-scripts.js
./cp.js
./excanvas.js
./backbone-worldwide.js
./jquery-plugin.js
./.found
./app
./app/crud-sel.js
./app/screen-detach.js
./app/aligator.js
./app/crud-in.js
./app/giraffe.js
./app/screen-attach.js
./app/main.js
./app/crud-del.js
./app/mouse.js
./app/monkey.js
./app/screen-shot.js
./backbone-national.js
./backbone23.js
./ummap.js
./CONFIG
./backbone-ibm.js
./ieee754.js
./flot
./flot/cow.js
./flot/moo.js
./flot/cat.js
./flot/bull.js
./flot/dog.js
./flot/sheep.js
./lines
./droiddraw-r1b21
./droiddraw-r1b21/._readme.txt
./droiddraw-r1b21/readme.js
./droiddraw-r1b21/LICENSE.js
./jquery-1.7.js
./ole.js
./touch
./json2.js
./xls2txt.js
./DO.sh
./backbone-isp.js
with a slightly modified configuration file:
geee: ~/src/bash/js-files
$ cat CONFIG
application.js
excanvas.js
json2.js
jquery*.js
flot/*
backbone*.js
app/screen-*.js
app/main.js
app/crud-*.js
app/*js
*js
and this bash script:
$ cat DO.sh
PROJECT=/home/jaroslav/src/bash/js-files # top folder of the web-app
SUPERJS=${PROJECT}/all-scripts.js
CONFIG=${PROJECT}/CONFIG # your the priority file (notice *js)
FOUND=${PROJECT}/.found # where to save results
JSMIN=$HOME/bin/jsmin # change to /usr/local/bin/jsmin or some other tool
echo > $FOUND # remove results from previous run
if [ ! -x $JSMIN ]
then
TMPJSMIN=/tmp/jsmin.c
wget -q https://github.com/douglascrockford/JSMin/raw/master/jsmin.c -O $TMPJSMIN & FOR=$?
echo "fetching jsmin (by Douglas Crockford) from github"
wait $FOR
gcc -o $JSMIN $TMPJSMIN
fi
cat $CONFIG | \
while read priority
do
eval "find $priority|sort -n" | \
while read amatch;
do
grep -q $amatch $FOUND || echo $amatch >> $FOUND
done
done
echo minifying:
cat $FOUND
cat `cat $FOUND` | $JSMIN > $SUPERJS
you will find the "merged" script in all-scripts after runing the script:
geee: ~/src/bash/js-files
$ . DO.sh
fetching jsmin (by Douglas Crockford) from github
[1]+ Done wget -q https://github.com/douglascrockford/JSMin/raw/master/jsmin.c -O $TMPJSMIN
minifying:
application.js
excanvas.js
json2.js
jquery-1.7.js
jquery-plugin.js
jquery-ui.js
flot/bull.js
flot/cat.js
flot/cow.js
flot/dog.js
flot/moo.js
flot/sheep.js
backbone23.js
backbone-ibm.js
backbone-isp.js
backbone-national.js
backbone-worldwide.js
app/screen-attach.js
app/screen-detach.js
app/screen-shot.js
app/main.js
app/crud-del.js
app/crud-in.js
app/crud-sel.js
app/aligator.js
app/giraffe.js
app/monkey.js
app/mouse.js
all-scripts.js
cp.js
ieee754.js
ole.js
ummap.js
xls2txt.js
Let me know if you need me to explain the script or if it fails on OS X.
The following script will follow the order of your config file and use the patterns given
#!/bin/bash
shopt -s nullglob;
while read config; do
cat $config >> out.js
done < /path/to/config/file
I ended up building a solution which uses a json file to list all of the files required by the app. On the dev environment the files are individually loaded by the browser. On the production server, the big compiled file is loaded. On my dev machine, I manually run a command to iterate over each file, appending it to a big JS file and running YUI Compressor.
It's a little hacky, but here it is:
https://github.com/renownedmedia/js-compressor