angular-translate is not translating with loaded static file - angular-translate

I'm using the following angular files for translations:
angular-translate.min.js (v2.2.0)
angular-translate-loader-static-files.min.js (v2.2.0)
angular-translate-storage-cookie.min.js (v2.2.0 )
angular-translate-storage-local.min.js (v2.2.0)
angular-cookies.min.js (v1.2.22)
angular-translate works when I do the following:
$translateProvider.translations('en_us', {
"label.test": "It works."
});
But not when I attempt to use a static file...
My HTML:
<html data-ng-app="myApp">
...
{{"label.test" | translate}}
My app.js:
var myApp = angular.module('myApp', ['ngCookies', 'pascalprecht.translate']).config(['$translateProvider', function($translateProvider) {
$translateProvider.preferredLanguage('en_us');
$translateProvider.useStaticFilesLoader({
prefix: '/app/resources/messages/i18n_',
suffix: '.json'
});
$translateProvider.useLocalStorage();
$translateProvider.storageKey('lang');
}]);
My Get Response (with Content-Type set to: application/json):
{
"label.test":"It works from JSON."
};
The rendered HTML page shows: label.test
Additionally, there are no errors in my console. I also tried renaming the key to TEST, but that didn't work, either.
Any ideas?
Thanks.

Check that the path to your .json is correct. If it is not found, in your template, it will just print out label.test instead of the actual translation It works from JSON. just like it is doing.
Your app root is most likely app, so if your translation file is located in /app/resources/messages/i18n_en_us.json then try:
$translateProvider.useStaticFilesLoader({
prefix: '/resources/messages/i18n_',
suffix: '.json'
});
Also make sure your JSON is valid JSON. Remove the semi-colon at the end.
{
"label.test":"It works from JSON."
}

Related

How to load dynamic image from assets folder in NuxtJS

I have 2 problems:
If I use the variable in src:
I will get this link in the web and not exactly:
http://localhost:3000/~/assets/product/image/bg.png
Similar to the first problem.
I want to use dynamic css file in head() method:
export default {
head () {
const style = this.$cookie.get('app_style')
return {
link: [
{ rel: 'stylesheet', href: ~/assets/${style}.css }
]
}
}
}
To load dynamic images in the asset folder you can use require to tell webpack which image to load like so. In your template you can do:
<img :src="require(`../assets/img/${folderType}/bg1.png`)" />
Note: assuming folderType is defined in your script section
You can extract the require statement into a computed property(would make your template cleaner). So like so:
export default {
// ...
data() {
return {
folderType: 'folderTypeGoesHere'
}
},
computed: {
imagePath () {
return require(`../assets/img/${this.folderType}/bg1.png`) // the module request
}
}
}
Then in your template just use:
<img :src="imagePath" />
For your second problem, you could resolve to not using the tilde ~ alias and just use a relative path as I did in the image path example above.
It depends on your Nuxt version and also the bundler.
In Nuxt2 address starts with ~\assets\ however in Nuxt3 it starts with \assets\ .
Consider some png images in assets directory and the name of one of them is in img variable which can be changed dynamically.
If you are using Nuxt2 and Webpack, you need to use require like the following.
<img :src="require(`~/assets/${img}.png`)">
If you are using Nuxt3 and Vite
<img :src="`/assets/${img}.png`"/>

How to download a PDF in Vue

So, here I've got a locally stored file named "its_me.pdf" in the assets folder.
I'm trying to reference a download to the PDF using an HTML tag
<a href="../assets/its_me.pdf" download>PDF</a>
It is a real PDF file, if I go double click on the file manually I can see it display and it's real. However, when I go to my application on: http://localhost:4200/its_me (name of route in which it lives), and click on the link, I get a "Failed - No File" error.
Based on #AkashBhave answer I was able to get to work this way.
In my script tag:
data () {
return {
publicPath: process.env.BASE_URL
}
}
then in my template.
<a:href="`${publicPath}whatever.pdf`" download="download">PDF</a>
Alternatively with webpack, in your vue.config.js you add this;
chainWebpack: config => {
config.module
.rule("pdf")
.test(/\.pdf$/)
.use("file-loader")
.loader("file-loader");
}
then in the script tag;
data () {
return {
pdfLink: require("#/assets/whatever.pdf"),
}
}
Finally, in the template;
<a :href="pdfLink" download="download">PDF</a>
Relative imports should work by default with Vue. Try putting your PDF file into the /public folder of your application.
You can then reference the file using string interpolation, like so:
<link rel="icon" href="<%= BASE_URL %>its_me.pdf">
More information is available at
https://cli.vuejs.org/guide/html-and-static-assets.html#interpolation
If that doesn't work, something might be wrong with your Webpack or build configuration.

Internationalization with Handlebars

I'm trying to internationalize my application that uses Express and Handlebars. Is it possible to get Handlebars partials (fragments) to load and render the localization resource file?
Noting that I've already read this question: express3-handlebars and 18next-node - internationalisation based on page?.
Here is my directory structure:
views/
index.html
login.html
fragments/
frag1.html
frag2.html
frag3.html
locales/
index.json
login.json
fragments/
frag1.json
frag2.json
frag3.json
If necessary, I can separate the JSON files in the locales/ directory to be something like this:
locales/
en-CA/
index.json
...other files
fr-CA/
index.json
...other files
Here is the relevant code in my server.js file:
// ...
hbs = exphbs.create({
extname: '.html',
layoutsDir: [
__dirname + '/views'
],
partialsDir: [
__dirname + '/views/fragments'
],
helpers: {
'json': function(context) {
return JSON.stringify(context);
},
't': function(k) {
// ?
}
}
});
app.engine('.html', hbs.engine);
app.set('view engine', 'html');
The t helper is what I need help with. In my templates/template fragments, I have these:
<h1>{{ t 'pageTitle' }}</h1>
<p>{{ t 'foo' }}</p>
<p>{{ t 'moreThings' }}</p>
And my JSON file could look like this:
{
"pageTitle": "Hello world",
"foo": "Paragraph contents here",
"moreThings": "There are %d things"
}
Also how do I deal with the printf parameters?
Doing internationalization in your application means doing two things:
1) Determine which locale should be used
Depending on how you determine the used locale it can be difficult to do this inside a helper. Helpers do not have access to the request object for instance. To be honest i cannot think of a good way to do this inside a helper.
Personally i use the i18n-abide middle-ware to do internationalization. They have several options to determine the locale for a given request. Once locale is determined it is added as a property to the request object. So you only need to determine the locale once for each request. An other advantage is that you have also access to the locale outside the handlebars helper.
2) Access the resource files
To access the resource files from within a helper means that you should read and parse the resource files outside the helper. Parsing resource files every time you need to translate a string really hurts performance.
Here you also should use middle-ware. You can do something like the pseudo code below.
function setup() {
// Load resource files from disk and parse them.
var resources = { /* parsed resources*/ }
return function(req, res, next) {
var locale = determineLocalFunction(req);
req.getText = function(label) {
return resources[local][label];
}
}
}
Now you can use the req.getText function every where in your code. Personally i never use language labels inside a partial. Instead i pass all the language strings needed in a partial using a data object. The reason behind this is that i think partials should be as re-usable as possible. Using hardcoded language labels inside them makes them less re-useable.
When you do want to use the getText function in your partials you can pass to getText function to your partial.
Something like this:
var objectPassedToPartial = {
getText: req.getText
}
Use it like:
{{getText 'label'}}
Read more about Mozilla's i18n-abide solution, i really love it.

Including dojo/dom library to Spring Roo

How is it possible to include and use the dojo/dom library in Spring roo.
This:
<script type="text/javascript">
dojo.require('dojo/dom');
dojo.ready(function remAttr(){
dojo.removeAttr('theId', 'value');
}
);
</script>
results in:
"NetworkError: 404 Introuvable - http://localhost:8131/suivitrc/resources/dojo/dom.js"
dom.js
Could not load 'dojo/dom'; last tried '../dojo/dom.js'
Can anyone please help?
I think the version of dojo in roo is currently less than 1.7. This means you can remove the following line from your code because the remoteAttr function is part of dojo.js:
dojo.require('dojo/dom');
see here: http://dojotoolkit.org/reference-guide/1.7/dojo/removeAttr.html
The namespace => to module path is retreived by replacing periods (.), in short - you need to replace the slash with a dot. Your require should be
dojo.require('dojo.dom'); // blocking call? djConfig.async must be false
Since the error is in regards to the dojo.require specified path, this means your dojo.js is found and loaded (dojo.require is not undefined) - and baseUrl is not of concern to dojo modules.
The thing is, youre using the legacy loader to pull in an AMD module, in 1.7+ the require statement has a different look to it.
// AMD loader form is
function callbackFunctionOnComplete(dojoDom) { }
require([ "dojo/dom" ], callbackFunctionOnComplete); // non-blocking
So, how dojo.require works is following, assume that the parameter we pass as string is called 'module;
dojo.require = function(module) {
var parts = module.split('.');
1 - get toplevel namespace (global)
var packageName = parts.shift(); // first part is the package name
2 - get the filename (minus .js)
var id = parts.pop(); // the last bit
3 - translate everything in between to a path (relative to packagelocation)
var mid = parts.join("/");
4 - lookup package (from toplevel) location
var fullpath = // in pseudo
foreach dojoconfig.packages
iff obj.name == packageName
set to obj.location
5 append the rest and start downloading module
fullpath += mid + id + '.js'
transport.get(..... fullpath .....)
You need to configure dojo with dojo config. I prefer the form explained here:
http://dojotoolkit.org/reference-guide/1.7/dojo/_base/config.html#explicitly-creating-a-dojoconfig-object-before-including-the-dojo-core.
And you need to tell dojo where to find its stuff. An example:
var dojoConfig =
{
baseUrl : "/yourApp/js", // defines the js folder in your webapp
tlmSiblingOfDojo: false,
async: true,
parseOnLoad:true,
packages: [
{ name: "app", location: "app"}, // where it is in the js folder
{ name: "dojo", location: "lib/dojo" }, // where it is in the js folder
{ name: "dijit", location: "lib/dijit" },
{ name: "dojox", location: "lib/dojox" }
]
};
Also the require form you are using is deprecated. See http://livedocs.dojotoolkit.org/dojo/require

MonoRail - How to write JavaScript within .vm page

I'm using MonoRail and tried to write a tag within a .vm view to write some JavaScript:
<script type="text/javascript">
//<![CDATA[
$j(document).ready(function()
{
$j('#business_parentbusinesstype_id').change(function()
{
$j.ajax({
url:'http://localhost:88/admin/business/GetChildBusinessTypes',
data: { parentId: $j('#business_parentbusinesstype_id').val() },
dataType: 'script'
});
});
});
//]]>
</script>
You would think that this would work since it's an HTML page but it gives me this error:
Unable to process resource 'admin\business\new.vm': Encountered "\r\n url:\'http://localhost:88/admin/business/GetChildBusinessTypes\',\r\n data: { parentId: " at line 7, column 12.
Was expecting:
...
What am I missing?
I'm wondering if nVelocity is seeing the "$j" and trying to find it in the property bag and execute the "ajax" method. If the "$j" is the short-hand for jQuery, try changing it to the full "jQuery" and see if that works.
Monorail uses the $ sign for objects in the Property Bag. Some things you can do is you can either use the longhand(jQuery.someFuntion()), or move the js to its own js file that you then just include in your vm file.