What javascript library/template engine to use in this case? - javascript

I have to make a invite your facebook friends module which fetches the names, photos of your friends and allows you to message 'em. I need this to look like a integral part of my website so I have to style it. I fetch the json with friends' ids, names etc. and want to put those values in certain html tags and attributes. How do I apporach this? I can make it in jQuery but want to avoid jQuery spaghetti code with ragu of strings and vars. What lib/template engine do you recommend me? Ease of use and weight are the most important things. The website has jQuery already included.

I can make it in jQuery but want to avoid jQuery spaghetti code with ragu of strings and vars. What lib/template engine do you recommend me?
I’d suggest to use no big additional lib or template engine – I’d just keep using jQuery, and embed one of the sprintf for jQuery implementations that are floating around the net.
So you can define your “HTML template” for your output in one location as one string, and than replace placeholders in that string with variable values while your looping over the data in jQuery.
If you don’t like any of the sprintf-Jquery-plugins out there, here is another very simple and short function that implements just the basic string placeholder %s (but more than that you most likely won’t need anyway): http://www.nczonline.net/blog/2011/10/11/simple-maintainable-templating-with-javascript/.
(And if you have to insert values in multiple places of your template string, than have a look at my comment on the bottom of that page, where if have proposed a simple adjustment to Nicolas’ function, that implements the “argument swapping” feature of PHP’s sprintf, so that you have to pass values to the function only once, but can use them in multiple places in your template string.)

The easiest way to do this is to use the Requests dialog. The first thing you need to do is create an app. Once you have this you should be able to use the JavaScript example on the request dialog page.

Related

Go templating engine that also runs in the browser

I'm developing a web application with Go on the server, and the router will use PushState, so the server will also have to be able to render my templates. That means that I'll need a templating engine that works with Go and Javascript. The only one I've come across so far is Mustache, but it doesn't seem to be able to handle lowercase properties of structs, and there also doesn't seem to be a possibility to provide custom names like JSON:
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
So, is there a templating engine that is available in both Go and JavaScript, and that can handle lowercase struct properties?
As the comments above state, you can't expect any 3rd party library to be able to read lowercase properties on your struct, but it appears you are trying to use tags to represent alternative representations of your struct (as you can with the encoding/json library).
What you can do is use something like github.com/fatih/structs to convert your structs to maps and then range through to lowercase all of your keys (copying the values and removing the uppercase versions) and pass it into mustache.Render() as your context. If you want to use struct tags like the encoding/json library does, you'd have to use the reflect package and write a struct-to-map function that takes into account the tags on the struct (basic example given in the documentation here). There are some SO answers on how to write a struct-to-map function using reflection, which you can improve upon to add struct tag handling as you need.
To answer your question, I don't think this is something a current templating library does that also works with javascript, but it shouldn't be too hard to get working with mustache given the idea above.

Run Database Stored RegEx against DOM

I have a question about how to approach a certain scenario before I get halfway through it and figure out it was not the best option.
I work for a large company that has a team that creates tools for the team mates to use that aren’t official enterprise tools. We have no access to the database directly, just access to an internal server to store our files to run and be able to access the main site with javascript etc (same domain).
What I am working on is a tool that has a ton of options in it that allow you to select that I will call “data points” on a page.
There are things like “Account status, Balance, Name, Phone number, email etc” and have it save those to an excel sheet.
So you input account numbers, choose what you need and then using IE Objects it navigates to the page and scrapes data you request.
My question is as follows..
I want to make the scraping part pretty Dynamic in the way it works. I want to be able to add new datapoints on the fly.
My goal or idea is so store the regular expression needed to get the specific piece of data in the table with the “data point option”.
If I choose “Name” it knows the expression for name in the database to run again the DOM.
What would be the best way about creating that type of function in Javascript / Jquery?
I need to pass a Regex to a function, have it run against the DOM and then return the result.
I have a feeling that there will be things that require more than 1 step to get the information etc.
I am just trying to think of the best way to approach it without having to hardcode 200+ expressions into the file as the page may get updated and need to be changed.
Any ideas?
IRobotSoft scraper may be the tool you are looking for. Check this forum and see if questions are similar to what you are doing: http://irobotsoft.org/bb/YaBB.pl?board=newcomer. It is free.
What it uses is not regular expression but a language called HTQL, which may be more suitable for extracting web pages. It also supports regular expression, but not as the main language.
It organizes all your actions well with a visual interface, so you can dynamically compose actions or tasks for changing needs.

How to implement different languages on html page

I am just a newcomer developing an app with html/css/js via phonegap. I've been searching info on how to make my app be displayed in different languages and Google doesn't understand me.
So the idea is to have a button on index.html that let the user choose the language in which the app will be displayed, in this case Spanish/English, nothing strange like arabic blablabla....
So I guess that the solution must be related to transform all the text that I load in html to variables and then depending on the language selected display the correct one. I have no idea how to make this, and Im not able to find examples. So that's what Im asking for... if someone could give some code snipet to see how html variables works and how should I save user language selection...
Appreciated guys!
This can be done by internationalization (such as i18N). To do this you need separate file for each language and put all your text in it. Search Google for internationalization.
Otherwise you can look into embeding Google Translate.
This depends on the complexity of language-dependencies in the application. If you have just a handful of short texts in a strongly graphic application, you can just store the texts in JavaScript variables or, better, in properties of an object, with one object per language.
But if you expect to encounter deeper language-dependencies as well (e.g., displaying dynamically computed decimal numbers, which should be e.g. 1.5 in English and 1,5 in Spanish), then it’s probably better to use a library like Globalize.js (described in some detail in my book Going Global with JavaScript and Globalize.js). That way you could use a unified approach, writing e.g. a string using Globalize.localize('greeting') and a number using Globalize.format(x, 'n1') and a date using Globalize.format(date, 'MMM d').

Where to store element specific extra data in a web page; data- or javascript

I have some data that I need to associate with specific element such as an individual table row. This data contains information such as the current state, and a unique identifier that correlates to an SQL row. When the user interacts with the element I want to read out the unique identifier, and with that identifier, issue an AJAX request to let the user change the state of that element.
After researching, it seems that there are two camps as to how to embed this element specific information.
1) Using a data- attribute in the html5. My understanding is this will work in modern web browsers as well as older browsers that don't support html5. But while this works, it does not following the HMTL spec ( less than HTML5) and so it won't validate if you run it through a HTML syntax checker.
2) Store the additional data into a javascript array, object etc. The extra work with this is now you need a way to correlate the javascript data to the html element.
What are the pros and cons of using these two different approaches to storing the data? And what approach would you recommend?
Thanks!
I wouldn't worry about the data- attributes not passing validators. The attribute is in HTML5 because people were using similar, non-standardized, attributes for a long time specifically to solve this problem. Go ahead and start writing "HTML5" by using the parts of the spec that work, i.e. don't break in a certain browser, and using the HTML5 doctype. The W3C validator at least already supports the doctype.
As for which method to use, I think it really boils down to when you want to parse the information in the JavaScript interpreter: on page load or when the data is needed. I imagine it depends on just how much information you have as to which will be most efficient. But you can't go wrong with adding it to the HTML with a data- attribute or two.
Personally, I like adding the information to the HTML with data- attributes. In the scenario you describe, I would use data-state and data-rid (or similar) so that I don't have to further parse the information (it sounds like you are thinking of putting two bits of information in one data- attribute). This way, your table of information is truly complete: the data is presented to the user and the markup contains further information that could be necessary to a parser.
I'd definitely go with option (1) and either not worry about those attributes not validating or just validate your document as html5. It's simple. It works.
The "separation of concerns" theory that leads some people to option (2) is nonsensical for this sort of situation because if you put the data into a JS object of some kind you still need a way to tie it back to the actual html elements so then not only are the two not really separate, they're more complicated than they need to be on the client side, and the server side code needed to produce it in the first place is more complicated.
In option (2), no special correlation is needed any more than in option (1)—rather, less. You can put the data into a property of the DOM object that corresponds to the element. Why not make use of the basic feature of JavaScript that you can add properties to an object?
You've tagged your question with jQuery, so I'll assume you have it. You can use the .data() method to store arbitrary data and associate it with an element.
$("tr").first().data('sqlId', 1234);
assert($("tr").first().data('sqlId') === 1234);

Multi language support

I'm developing a HTML5 application that uses jQuery. I want to make it multi language: detecting user language and changing all literals to user's language.
I think that one approach is to use one HTML file for each language supported, but it is a waste of space.
Another approach could be use jQuery to change all literals to user's language. But I'm not sure how to do this.
What do you think? Is there a better approach?
UPDATE:
I've forget it to say that I have some literals inside JavaScript too.
Coulnd't you do some sort of server-side query to the user's language and then load the appropriate text automatically? Maybe even a CMS is appropriate here.
For all the Javascript code, I would use String literals as a variable. So you can load a different language file appropriate to the user language.
File english.js:
var messages_siteA1 = "This is an alert.";
var messages_siteA2 = "...";
// ...
File german.js:
var messages_siteA1 = "Dies ist eine Warnung.";
var messages_siteA2 = "...";
// ...
And in your Javascript:
alert(messages_siteA1);
Or am I missing the point here? ;)
In the HTML5 Demo of my, the "HTML5 Word Clouds",
http://timc.idv.tw/wordcloud/
(source code can be found at https://github.com/timdream/wordcloud)
I wrote separate HTML for different languages, and includes a single set of Javascript files. For literal strings with in the script, I collect them into an object (named T) and put it into <script> block of each HTML files.
This give me the flexibility to customize pages for each language; as you can see, I listed CNN as example in English version, but list other sources in the Chinese version.
If you absolutely have to do it at client-side, how about using a json or xml file to store your translations? This avoids the trouble of creating copies of the same page. For example, in your json. you'd have "welcome_eng": "welcome" and "welcome_fr": "bienvenue", etc.
Then you load the appropriate one using javascript, as in, get the variables like this:
blablabla=["welcome_"+language]
Or, if you want even less work, your welcome text's div will have the id "welcome", then your javascript gets the id and add the appropriate content.
It mostly depends on how dynamic or static your pages are: If they contain much text, than it will be easier to duplicate the page for each language. In this case it is very important to carefully isolate HTML from CSS and scripts. All CSS and scripts should be stored in separate pages, in order to avoid having to update all translations whnever you update a style or a script.
OTOH, if it is mostly dynamic, than it makes sense to replace text snippets by their translation when creating the page. But I wouldn't do the text replacement client-side (jQuery). It's a server-side job.
Edit: If you have javascript literals, you should then of course keep them side by side with the HTML, either in the HTML file or in a separate .js file. But it remains up to the server to deliver the contents in the correct language.

Categories

Resources