How to include a definition language file in javascript? - javascript

I have a big javascript file common.js
with all my functions and stuff...and i would like to write a separate file Js
to store only the definitions for all the alert/courtesy messages etc
spread along the file...i don't want to seek and change one by one...
i have created something like this in php, where I have my file, en.php / fr.php /de.php for each language i need...
i was wondering:
1. if i can do the same in Js
2. if there is any way to use the php instead...so woudl be even better to have just one and only file to edit
thanks

Sure -- all you need to do is to create a definitions file for each language that just creates an object with the needed name: value pairs. Your existing JS can then insert defsObject["name"] wherever needed. Your PHP would then determine which of the JS definition files to load by changing the src value of the script tag.
If you are unfamiliar with the object notation, there's loads of examples available on Stack Overflow (tagged JSON).

I don't believe there's a satisfying way using js to include the definitions.

Related

How to add localization toexternal js file in Asp.net MVC?

Im pretty much stuck, because i cant figure out how to "call" resource files in .js files. I have a login view, on this view i call MVC render method to generate script tag.
#Scripts.Render("~/Scripts/Login.js")
in my Login.js i have a variable :
var yes = "Resources.Resource.Yes";
which should be tranlated to Yes, or Ja, or anything else depends on which cultureInfo is set. Its pretty straight forward to do if i keep script files inside of my view, because then i just call #Resources.Rescource.Yes and it will work, but if script file is external, then it wouldnt work. How do i solve this?
The answer to this question would be largely opinion-based.
There are three main approaches i encountered working on various projects:
Localization handlers. You define the resources keys in javascript, in $(document).ready() you use ajax to get the localized values from a controller/httphandler dedicated to this and replace keyed text.
In-line js. Basically, you dump external .js and render scripts inside <script> tags in your views/pages.
Global variables. In the view your define global variables, like so:<script language="text/javascript">var myString='<%= Resources.MyString %>';</script>, then use the variable inside included .js.
Personally i prefer approach n 3 -> you can have a single place in code to create all variables and the page loads in one go.

Using resource files (.resx) in javascript

I'm trying to use localization in my project but I can't find a way to access my resx files from javascript. I have been looking around a bit and I don't think the 'AJAX call' method would be ideal for my project since I have quiet a lot of string that need to be fetched and it would just have to spam the server hard!
if I just put it in my HTML then it works with this code:
#using Resources
<p>#Html.Raw(ISt_Localization.January)</p>
I guess one of the things I could do is put all the strings in a hidden div and then get the content from the divs in my javascript but this wouldn't be very effective..
I had a similar situation and in my case, I created a separate partial view which only contained a javascript block where I put all the resource strings required for use in client side logic. Every resource string was defined as a javascript variable. You could also create an associative array.
In your partial view:
var Resources = {
January : "#Html.Raw(ISt_Localization.January)",
February : "#Html.Raw(ISt_Localization.February)",
...
};
You can also try the below thing directly
#using Resources
<script>
var value = '#Resource.January';
/* work with value
.......
.....
*/
</script>
I took a totally different approach.
I want to have the resource strings required by my Javascript files be part of my resx files.
Every key in my resource file which starts with js has to become available in Javascript.
In global.asax, in Application_OnStart I build Javascript files for all supported languages on the fly.
Because this only happens at the start of the application, it does not matter if it takes a few seconds.
Advantages:
All translations in one place (in the rex files which you use for your .NET application (C# or VB), but also for your Javascript code
Always up to date
Very fast, because we are going to use variables to get the translations
Building the Javascript file is easy.
Iterate through all key value pairs in all resx-files. Just pick out the keys starting with _js_.
Save the key value pair in the Javascript file.
So if the key value pair in the resx-file (languageSupport_es.resx) is '_js_Hello', 'Hola',
I write in my Javascript file (languageSupport_es.js) var Hello = 'Hola';
So alert(Hello) will give you 'Hola' if the current language is Spanish.
The only thing I now have to take care of, is using the right 'language Javascript file' is loaded before my other Javascript files.
So if the language is Spanish, I ONLY include my 'Spanish language Javascript file' (languageSupport_es.js) first.
Easy no? If somebody is interested, I can show some example code...

Is it possible to use Mojolicious tag helpers in external JS files?

I am currently working on cleaning up a little web app I've written in Mojolicious. As part of that cleanup I am separating out my javascript into the public directory from my html.ep files.
The problem I have though is I don't seem to be able to reference tag helpers any more, like 'url_for' or even referencing values in the stash such as '<% $stashvalue %>'.
Any idea's on how or if I can do this is very much appreciated.
cheers.
The stuff in the public directory is served statically, optimally by your webserver, not by Mojolicious or Plack, so that file does not get processed by Mojolicious, thus <% $stashvalue %> not meaning anything.
A solution would be to embed those parts of javascript that need to access server side variables in the mojo templates - rather ugly, but less code to be written.
Another one would be to make an ajax call from your javascript files, when they are loaded, and get the values sent by the server - more elegant, but more code to be written.
Another one that I can think of, would be to move those javascript files under a folder that gets processed by Mojolicious and include them parameterized - in your html.ep file that needs that js file, do :
<script type="text/javascript" src="http://example.com/url/served/by/mojo/?param1=<% $stashvalue %>&param2=<% $stashvalue2 %>"></script>
And, in the controller that responds to /url/served/by/mojo/, render that js file, with the params replaced by the ones from the query. As an alternative, you could store/receive those params also on the session
As usually in Perl, there is more than one way to do it.
What I typically do is encapsulate most of my javascript in function calls or objects in pure javascript files. Then in my templates I include those pure javascript files and use the api that I built in those files from the template, interpolating the server-side variables into the arguments of the functions. You can peruse the code for Galileo to see several examples.
For example, see how this template passes stash values to this pure javascript file's functionality.

Grails: Javascript files in views folder

I'd like to split my views in Grails into 2 files a .gsp file and a .js file so that I get a cleaner Javascript separation from my views. So here's an example:
views/index.gsp
views/index.js
views/home/index.jsp
views/home/index.js
But when I simply add the index.js script reference like this:
<script src="index.js" type="text/javascript"></script>
all I get is a 404.
Does anyone knows how to deal with this?
A great benefit would be to have the ability to use view data inside the index.js file to produce the desired content.
Matthias.
Actually, it should be perfectly possible to serve a JS file (or any other file type) as a GSP from your grails-app/views/ directory. The only thing you have to do, is define a suitable URL mapping for those GSPs, e.g.:
"/javascript/home/index"(view:'/home/index.js')
With this URL mapping, you can put your JS code into grails-app/views/home/index.js.gsp (note the trailing .gsp) and you can use any grails tags in your JS source. To ensure that your JS is delivered with the correct content type, you may want to place
<%# page contentType="text/javascript"%>
at the beginning of your GSP.
Unfortunately, the createLink tag doesn't support link rewriting to views, but it should be easy to write your own tag to create those links.
Anyways, keep in mind that this won't have a very positive impact on your app's performance. It's usually better to have static JS files (and also serve them as static resources) while passing dynamic stuff as parameters to JS functions for example. This will also keep you from some headaches wrt. caching etc.
The idea is good, but Grails has this directory structure for a reason. The view folder is intended for a certain artifact type (views)..
You could clone your view folder structure under web-inf, but that gives you more work as I guess the idea behind this is to keep related files close together for convenience reasons.
Even though I'm not to excited about storing Javascript together with the view I loved Robert's idea of hooking into the build process by using build events to copy javascript sources into the right directory! If you decide to go down that road you might as well compress the sources while you're at it. ShrinkSafe is popular library.
I don't think you are allowed to access js inside views/
if you need to do that ... here is the trick
create your js and rename it with myjs.gsp (use "")
iniside _myjs.gsp type you js
... write down you js in here ...
inside you gsp (for example: index.gsp, view.gsp, etc)
type this tag to upload you js
Update 2:
Grails offer the possibility of hooking into the build lifecycle using custom events.
An event handler can be written which synchronises all JavaScript files under grails-app/views with the target folder of web-app/js.
Place the custom code in $PROJECT/scripts/Events.groovy. The PackagingEnd is a good target for the invocation, since it happens right after web.xml is generated.
eventPackagingEnd = { ->
// for each js file under grails-app/views move to web-app/js
}
Update
If you'd like the JavaScript files simply 'meshed' together, you can do that using symlinks, e.g.:
grails-app/views/view1/index.js -> webapp/js/view1/index.js
As far as I know, there is no way of forcing grails to directly serve content which is outside of web-app.
Alternatively, you can inline your JavaScript, but that can have performance implications.
JavaScript files belong under web-app/js.
Then you can reference them using <g:javascript src="index.js" />.

Executing groovy statements in JavaScript sources in Grails

There are essentially 2 places to define JavaScript functions in Grails, directly in a element on the GSP, and within a separate javascript source file under /web-app/js (for example, application.js). We have defined a commonly reused javascript function within application.js, but we also need to be able to generate parts of the function dynamically using groovy code. Unfortunately, ${some groovy code} does not appear to be processed within separate javascript source files.
Is the only way to do this by defining the javascript function within a script tag on a GSP page, or is there a more general solution? Obviously we could define the javascript function in a script tag within a template GSP file which would be reused, but there is a lot of push to keep our javascript functions defined all together in one place (i.e. the external javascript source file). This has performance benefits as well (the javascript source files are usually just downloaded once by each client's browser, instead of reloading the same javascript functions within the source of every html page they visit). I have toyed around with the idea of breaking the function up into static and dynamic pieces, putting the static ones in the external source and putting the dynamic ones in the template GSP, then gluing them together, but this seems like an unnecessary hack.
Any ideas?
(edit: It may sound like the idea of dynamically generating parts of a JavaScript function, which is then downloaded once and used over and over again by the client, would be a bad idea. However, the piece which is "dynamic" only changes perhaps once a week or month, and then only very slightly. Mostly we just want this piece generated off the database, even if only once, instead of hard coded.)
An easy solution to keep your JavaScript unobtrusive is to create a JavaScriptController and map its actions "/js/*" by adding this to your UrlMappings.groovy file:
"/js/$action"{
controller = "javascript"
}
then just create an action for each dynamic JS file you want, include in in your layout <HEAD>, and presto, you've got a JS file that you can insert Grails snippets into! :)
Note: I've found that there's currently a bug in Grails that doesn't map file extensions to content-types properly, so you'll need to include <%# page contentType="text/javascript; UTF-8" %> at the top of your view files.
This is a great solution. I would like to offer a suggestion to use somthing other then a mapping of "/js/$action" because this is no longer going to allow you to access you javascript files in /web-app/js/. All your javascript files would have to be moved to a the directory your controller would point to.
I would use something like
"/dynjs/$action"
This way you still can point to files in the /web-app/js/ files with out conflict and enjoy the benifits of gsp tags in javascript files
Please correct me if I'm wrong.
Or this... have a tag/service/dynamic method that lets tags write out their JS+CSS+whatever else, to a "cache" which is used to build the JS+CSS resources by a different controller.
Full concept here: [http://www.anyware.co.uk/2005/2009/01/19/an-idea-to-give-grails-tags-esp/][1]
If you want to use models created by the controller (that rendered HTML page which reference the Javascript in which you intend to use groovy code) in the Javascript code, then you can use this technique:
This technique does not need to change URL mappings and does not require you to create extra controller.
In your view GSP add javascript as follows:
<script type="text/javascript">
<g:render template="/javascript/yourJavascriptFile"/>
</script>
In views folder create a "javascript" folder. And create a file named:
_yourJavascriptFile.gsp
You can not only use all the GSP code in your _yourJavascriptFile.gsp file, but you can also use all the models created in your controller (that is rendering the view).
NOTE: There is nothing special about javascript folder. You can name it anything you want OR use an existing view folder. This is just a matter of organizing and identifying your HTML spitting GSP from Javascript spitting GSPs. Alternatively, you can use some naming conventions like: _something.js.gsp etc.
Name your scripts like this
/wherever/the/js/files/are/thescript.js.gsp
The gsp code inside will be rendered correctly by grails. This works, but I have no idea if it's considered a Good Idea or not.
There is another way - pass in the generated code into a function that expects closures. Those closures is generated by the program of course. The generated code is of course inlined/script-tagged in the gsp page.
it may or may not work depending on the nature of the code being generated. But i suspect it will work, and if it doesnt, minor tweaking to the coding style of your javascript will definitely make it work. Though, if these 'generated' code doesnt change much, this quite overkill imo.

Categories