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...
Related
I currently have a Java Spring project where the bulk of the front is in AngularJS, HTML, etc. I currently have an application.properties file that holds:
name:myName
idNum:8888888888
password:squirrels
contextPath:/ilovesquirrels-ui
server:0000
ui.firstLink: www.google.com
ui.secondLink: www.yahoo.com
ui.thirdLink: www.w3schools.com
myBool: False
The first five seem to read in automatically to a place I cannot seem to find. The last four, I'd like to access in Javascript to store the urls and the boolean. I'd like to write something in JS like:
var myLink1 = "something that accesses ui.firstLink in application.properties";
var myLink2 = "something that accesses ui.secondLink in application.properties";
var myLink3 = "something that accesses ui.thirdLink in application.properties";
Right now, I am reading information from a Javascript file that holds a JSON object that I'd eventually like to get rid of. It was all the same information as application.properties, except it is more visible to the end user. How do I get the links from my application.properties file into Javascript variables?
I don't like to mix JavaScript with the server-side language as it:
makes life harder for editors
is harder to read
couples JS with the server-side technology
Therefore, I would put the desired variable expressions as meta tags or data-attributes and then access them using JS.
<body data-uifirstlink='<%=properties.getProperty("uifirstLink")%>';
accessed with jQuery by: $('body').data('uifirstlink');
note: ideally, these data attributes should be as contextual as possible (instead of body choose a more specific place).
<meta name='uifirstlink' content='<%=properties.getProperty("uifirstLink")%>' />
accessed with jQuery by: $('meta[name="uifirstlink"]').prop('content')
A service for retrieving properties is not good because:
You need to wait for the page to load to run the call and use the variables
You have unnecessary Ajax calls
You create more coupling between client and server
Finally, you could consider cookies or headers, but I don't think is so straightforward.
You could create a jsp file with this:
<script>
var myLink1 = '<%=properties.getProperty("ui.firstLink")%>';
</script>
If you want to use spring, create a PopertiesPlaceHolderConfigurer and use spring tags in jsp. See here
I am new to web dev and I have a text file that I created using C# to collect some data from a website. Now I want to use that data to make graphs or some way to show the info on a website. Is it possible to use I/O in javascript or what is my best option here? Thanks in advance.
You have several options at your disposal:
Use a server-side technology (like ASP.Net, Node.js etc) to load, parse and display the file contents as HTML
Put the file on a web server and use AJAX to load and parse it. As #Quantastical suggested in his comment, convert the file to JSON forma for easir handling in Javascript.
Have the original program save the file in HTML format instead of text, and serve that page. You could just serve the txt file as is, but the user experience would be horrible.
Probably option 1 makes the most sense, with a combination of 1 + 2 to achieve some dynamic behavior the most recommended.
If you are working in C# and ASP then one option is to render the html from the server without need for javascript.
In C# the System.IO namespace gives access to the File object.
String thetext = File.ReadAllText(fileName);
or
String[] thetextLines = File.ReadAllLines(fileName);
or
If you have JSON or Xml in the file then you can also read and deserialize into an object for easier use.
When you have the text you can create the ASP/HTML elements with the data. A crude example would be:
HtmlGenericControl label = new HtmlGenericControl("div");
label.InnerHTML = theText;
Page.Controls.Add(label);
There are also HTMLEncode and HTMLDecode methods if you need them.
Of course that is a really crude example of loading the text at server and then adding Html to the Asp Page. Your question doesn't say where you want this processing to happen. Javascript might be better or a combination or C# and javascript.
Lastly to resolve a physical file path from a virtual path you can use HttpContext.Current.Server.MapPath(virtualPath). A physical path is required to use the File methods shown above.
I assigned a string to a javascript string object, such like :
var word = "Please input correct verb"
I want this string be in control by resource file in asp.net project. Does it provide the function to replace the string using a ASP.NET syntax to switch languages?
<%$ Resources:Registration, correctverb%>
Thanks.
There are various l18n projects for JavaScript, e.g. http://i18next.com/
If you have ResX files in your ASP project and you want them as JavaScript or JSON files you can convert them here; or via the REST API you could convert a resource file as follows:
$ curl --data-binary #messages.resx \
http://localise.biz/api/convert/resx/messages.json
(example in cURL, which I guess you may not have if you're on Windows)
A common approach for this is creating an HTTP handler that evaluates requests for say files with the extension *.js.axd (or whatever extension you come up with) and then parse the javascript file by replacing defined tokens with the actual localized resource value.
It may be costly only the first time the file is requested but then everything should run smoothly if caching is applied. Here's an example of how to create a handler, parsing the file should be trivial. You could use the same syntax to define localized strings on your file: <% LocalizedResourceName %>
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.
I'm developing a facebook app right now all by my lonesome. I'm attempting to make a javascript call on an onclick event. In this onclick event, I'm populating some arguments (from the server side in php) based on that item that is being linked. I'm inserting a little bit of JSON and some other stuff with funky characters.
Facebook expects all the attribute fields of an anchor to be strictly alphanumeric. No quotes, exclamation marks, anything other than 0-9a-Z_. So it barfs on the arguments I want to pass to my javascript function (such as JSON) when the user clicks that link.
So I thought, why don't I use my templating system to just autogenerate the javascript? For each link I want to generate, I generate a unique javascript function (DoItX where X is a unique integer for this page). Then instead of trying to pass arguments to my javascript function via onclick, I will insert my arguments as local variables for DoX. On link "X" I just say onclick="DoX()".
So I did this and viola it works! (it also helps me avoid the quote escaping hell I was in earlier). But I feel icky.
My question is, am I nuts? Is there an easier way to do this? I understand the implications that somehow somebody was able to change my templated local variable, ie:
var local = {TEMPLATED FIELD};
into something with a semicolon, inserting arbitrary javascript to the client. (and I'm trying to write code to be paranoid of this).
When is it ok (is it ever ok) to generate javascript from the server? Anything I should look out for/best practices?
Depending on your application generating JavaScript in your templating language can save a lot of time but there are pitfalls to watch out for. The most serious one being that it gets really hard to test your JavaScript when you don't have your full templating stack available.
One other major pitfall is that it becomes tempting to try and 'abstract' JavaScript logic to some higher level classes. Usually this is a sign that you will be shaving yaks in your project. Keep JavaScript login in JavaScript.
Judging from the little bit of information you have given it your solution seems sensible.
If you must generate javascript, I would suggest only generating JSON and having all functions be static.
It more cleanly separates the data, and it also makes it easier to validate to prevent XSS and the like.
JS generated from server is used in lots of areas. The following is the sample from a ASP.NET page where the JS script is generated by the framework:
<script src="/WebResource.axd?d=9h5pvXGekfRWNS1g8hPVOQ2&t=633794516691875000" type="text/javascript"></script>
Try to have reusable script functions that don't require regeneration; and 'squeeze' out the really dynamic ones for server-side generation.
If you want to feel better about it, make sure that most of your JavaScript is in separate library files that don't get generated, and then, when you generate code, generate calls to those libraries rather than generating extensive amounts of JavaScript code.
it's fine to generate JS from the server. just bear in mind not to fine too big a page from the server.
Generally speaking I avoid ever automatically generating JavaScript from a server-side language, though I do however; create JavaScript variables that are initialized from server-side variables that my JavaScript will use. This makes testing and debugging much simpler.
In your case I may create local variables like the following which is easy to test:
<script type='text/javascript' language='javascript'>
<!--
var FUNC_ARG_X = <%= keyX %>;
var FUNC_ARG_Y = <%= keyY %>;
var FUNC_ARG_Z = <%= keyZ %>;
//-->
</script>
<script type='text/javascript' language='javascript'>
<!--
function DoCleanCall(arg) {
// Whatever logic here.
}
//-->
</script>
now in your markup use:
<a href='#' onclick='DoCleanCall(FUNC_ARG_X);'>Test</a>
Now of course you could have embedded the server-side variable on the <a/> tag, however it is sometimes required that you refer to these values from other parts of your JavaScript.
Notice also how the generated content is in it's own <script> tag, this is deliberate as it prevents parsers from failing and telling you that you have invalid code for every reference you use it in (as does ASP.NET), it will still fail on that section only however.