Node.js: Client-Side Templating v/s Server-Side Templating - javascript

I have been trying to learn Node.js for a few days now, but there is one thing I am confused about.
What is the difference between a client-side templating solution like JQuery templates and a server-side solution like Jade for Node.js?
What are the uses for each? Where are they used? Can they be used together? Is there an exampe of both of them being used together if so?
I just can't get my head around this. Would be nice to have an overview of things from somebody around here...

The biggest thing that should be considered about client-side vs server-side templating is that client-side templating will not work if JavaScript is disabled on the client for whatever reasons.
Otherwise it's not such a big difference. It's mostly up to whether you want to generate your markup on the server, or on the client.
A typical reason to use client-side templates is if you have an application which loads more data from the server using ajax, websockets or such. In such a case you might want to have a client-side template for rendering the newly loaded data.
For example:
In an application I wrote, I used ejs templates on server to generate the basic markup: The head, body, footer, etc. - content which doesn't change.
The application uses socket.io, which sends the client some events and data from the server. To display this data, I used Knockoutjs' client-side templating.
So in my case it's kind of a hybrid approach. The reason I did it like this is because the markup I generate on the server will immediately show once the page loads. The data which comes from socket.io could have also been rendered into HTML on the server, but that would require more bandwidth to send than sending simple JSON objects or such, so I opted to render them on the client.
Obviously I could have used a client-side template for the entire site, but I saw no benefit in rendering the static parts on the client. It would have just made the client-side code of my application more complicated.

Related

Do javascript templates save server performance over php templates?

So I'm trying to create a website that almost runs only on the clientside using symfony2, backbonejs and underscore.
symfony2 for the backend and backbonejs for the frontend.
Symfony2 uses twig templates which get compilled into php classes by the server.
Would it save server performance to avoid twig templates as often as possible and use javascript templates (underscore) instead?
Or doesn't it make a difference since the templates need to be fetched from the server anyway?
Fetching a static file from the server is always going to give you better server performance than having the server process a template and return the result. The chances of that being significant are pretty low though, and you'd have to benchmark it to find out how much difference it makes.
Fetching a static template file from a server and fetching a dynamically generated data file to inject into it may or may not give you better performance then having the server insert the data into the template. You'd have to benchmark it.
Performance benefits of using client side templates almost always come from:
Having to fetch small data files from the server instead of HTML documents
Modifying page of an existing page instead of clearing it and loading a completely fresh one
The benefits do have to be weighed against the costs though (which are either the additional work to make the site continue to work if JS isn't available combined with the use of pushState and friends to have workable URLs or the fragility and search engine invisibility of a site completely dependant of JS)

AngularJS client side data binding and server side templating

AngularJS uses two-way client side data binding (from AngularJS Developers guide):
Has anyone consider using mix of server side templating engine with AngularJS two-way client side data binding. Something like this:
I am thinking about using AngularJS just for parts(components) of the page? Would it be good idea?
I would like to hear if you already had experiences with similar approach and what were drawbacks and advantages...
Angular is a complete UI rendering client framework. You can feed data into it, and it will render the proper html. On it's own Angular is a templating solution completely de-coupled from any server.
What you're attempting to do, is re-couple your Angular application to your server. It will be more work, there will be very few benefits, and you'll lose your ability to switch server technologies but keep your angular application untouched.
In essence, you don't want to do this for the same reason you wouldn't want to have your server rendering JavaScript for you... it's just less obvious because of all of the years we've been rendering all of our HTML at the server.
The end result is what's important. That the UI works properly and the application is easy to maintain. If you find your solution to be easier to maintain, then you should do it. I have a hard time imagining much being easier to maintain than straight HTML and JavaScript with a server that does nothing but host JSON.
I had the same dilemma as you have, I come from a background of using SMARTY as a server side template engine and we recently started using AngularJS.
I think mixing both solution would be appropriate in the the essence of total separation. i.e don't mix part of your page with both technologies but use both technologies separately.
For instance if you have a listing page where users will not interact with it at all, you may use server side template perfectly.
But if a page involve lots of manipulation and user side interaction in this case Angular is what you should use.
If you are using SPA (single page application) don't use server side template at all.
In a cordova app we recently made, we used a kind of a mix. Fix content like forms, lists, headers and menues we did in the angular way, some parts like content from an RTE or often changing templates we added with the directive ngBindHtml. The idea behind is to be flexible in the content pages of the app if the client want to change layout or want to put currently unknown content to it.
But i would suggest: if you can easy maintain the app (no long deployment/approval process) you should do it the angular way (but with no SEO in mind;).

Should I send raw data or Html as an Ajax response?

I have a site written in Asp.net webforms. It uses ajax heavily.
Most forms on the site are submited with javascript. Javascript validates the input and sends it to /ajax.ashx on the server. The server processes the request and sends back a JSON response. My javascript uses the JSON to create html, which it inserts into the Dom.
I'm making a new version of my website written using asp.net MVC3. I've been looking at tutorials on this subject, and some of them recommend doing ajax in a different way. Rather than sending data and then building + inserting html with javascript, they create html at the server, and use javascript only to insert it into the Dom. For instance, in this tutorial.
Which way should I use? Using the new method will be quicker, but is it better?
That's a subjective question. Both approaches are possible and there is no better way. There are pros and cons of each approach.
Building the HTML on the server is easier and will require you less efforts but consumes more bandwidth compared to the first approach.
If you decide to go the first way you could use some client side templating framework which might help you simplify the generation of DOM elements on the client.
Creating html code directly into the server and injecting it with an ajax call is very fast and simple, the real problem is that in that way your service is bound to be used with that specific application. By sending RAW data you allow any app to use that data in any way, without bounding it to a specific application.
returning json feels more flexible to me; you can change what happens with your json response, like the layout it results in. If you return html you return data mixed with layout. This doesn't feel right to me.
I believe it is better to separate the layout from the actual data. That is why you should pass data between your scripts and not HTML.
If you go about it sending HTML, consider that you would have to build valid HTML and CSS, which might not sound hard at first but then you'll start using CSS that is not loaded in the file calling the ajax, etc.
Always separate content (data) from layout. That's why there is HTML and CSS, to separate layout from data. So why mess things up by mingling HTML between data?
Building the html serverside will probably be faster and not bog down the client which is important. Rendering data into HTML with javascript takes time and not every browser is fast with js (i.e. older versions of IE) so things can slow down if you're doing a lot of this.
Like previous posters said, it's kinda subjective because it depends on how much you're offloading to the client. I'm of the opinion that if you can do things serverside, you should.
If you are going to be using this service to return JSON to other applications/clients, then it's probably a good idea to just leave it as JSON and let the client do what it needs on their side.

Are javascript templates only useful for inserting small items into the DOM?

I recent came across Javascript templates and have become quite intrigued.
I am building a large PHP application using the MVC pattern. Templating is handled by the rather awesome Twig.
I recently came across a javascript implementation of twig.
I have also read quite a bit about using javascipt template engines.
Now, in my application, the application generates a the full page for standard requests as fallback for users without javascript. For AJAX requests, it can generate the content part of the page (no <head>, <body> etc).
The ajax response object is currently just a the rendered HTML content, which is then inserted into DOM.
Should I instead return a response object containing a compiled javascript template and the objects to be inserted into the template? What are the benefits of doing that?
From the posts I have read, the javascript templates were only small snippets representing a small part of a page, for example displaying a comment on a blog post during the instant that the user has submitted it.
Are javascript templates only useful for inserting these sort of small "pieces" in a page?
Yes
A recent project I was on got "client-side template fever" and we used the dang things for every single template.
With every template library I've used (which is two or three), the error messages you get are not very good. If you have a huge template that operates on a fair amount of data, you'll quickly find the u.foo is null or not an object error message increasingly frustrating.
The best-practices I've settled on is:
Return a full HTML snippet (from the server) if it's a template that is seldom loaded. If you are only loading that HTML once on a page, then you might as well send it down populated right? This also encourages you to keep your logic up on the server, where it probably belongs.
Use client-side templates for small, repeated templates. Your blog comment example is probably a good one. I've found the most success when my client-side templates are pretty small (< 10 lines)
Use a logic-less template engine. The more logic allowable in a template, the harder they are to read/maintain. Plus, some of that logic should probably be in your business layer, not down in some JavaScript template. In other words, they force you to separate your presentation from your logic (which is good).
PS: It is cool that both your client and server-side templates could use the same templating engine. This will make developers on your project much more productive.
Depending on the scale and requirements of your application, you should take into considerations the following:
don't go rampant on Ajax; Ajax is not WebSockets, so use it sparingly. Plus, client-side execution speed is always key; AJAX is slow when compared to dumping as much resources as possible + using them when you need them; for example, you can send to javascript userdata = {name:'xxxx',address;'yyyy', ...} and using that, instead of requesting name and address via AJAX only when you need them.
it is recommended to use a global PHP var $sendData (or something like that) and right after plasting HTML, you send the $sendData with an easy <script>data = <?php echo json_encode($sendData); ?></script>
javascript templates add up to execution speed. which makes it reasonable to do the alternative, that is, separating everything that is dynamic and caching static resources like javascript functions
you can't, and I quote return a response object containing a compiled javascript template, not without residing to some server-side javascript engine that does the compile job prior to returning it
for your personal welfare, it will always boil down to how fast, easy and painlessly you respond to maintaining the application; there's no point in using super beta experimental frameworks, ports and kits over which you have limited control
Work smart, not hard.
Good luck mate.
You could also look into the Distal http://code.google.com/p/distal templating engine.

Templating with Javascript or Django?

I'm building a Django web application which has a lot of html generated on the fly by ajax requests. Right now I use Django's templating language to build up html and then pass this new HTML as a string in JSON object which is then injected into the page with jQuery.
This works fairly well, but with Javascript being so fast in modern browsers and with so many javascript template libraries being made I'm wondering if I should push everything clientside.
So my question is: Given the that my average "page" with all requests to and from it has to compile around ~300 templates (each of about 15 or so lines with 5 or so substitutions) out into HTML during its lifetime is there significant performance advantage to doing templating in the browser?
In addition can anybody reccomend a 'fast' Javascript templating library? I've heard good things about underscore.js, mustache.js and jQuery template.
The (massive) advantage of sticking with Django templates is that you only need to use one templating language, which retains the same capabilities regardless of the page you wish to generate. If you find that you're having performance issues then you should consider looking into caching template fragments.
I don't think an hybrid client and server templating architecture is bad. As long as you code a template only in one of the environment.
Every time you generate a page server side, an amount of processing time and some network bandwidth is consumed. This is what you pay if you use hosted servers.
While the user's browser is awaiting idle on a generally idle computer for the response.
If you send the template on the client(HTML + JS), they can be cached, for the session or even days, if the user do not delete them.This reduces the network traffic to deliver the same content various times. As the data are generally smaller than their equivalent rendered HTML.
As you point today's Javascript engines are really fast, as well as the computer they run it. Each time you sent the rendering work to the client, you save some processing time for your server and deliver faster the data.
We're at the other extreme side, as we run all on the client and that's why we created PURE for an ultra-fast client rendering. Our app looks very fast as a result of this decentralisation.
Why do you pass the HTML as JSON? Just send back the HTML and use jQuery's $.html() function to put it in the <div> or whatever.
As for templating in Javascript, there's Pure. If you're using jQuery (I'd recommend it), it already has a template engine.
It may be possible to make templates of dual purpose - to that they could be rendered into placeholders for the replacement by js and at the same time they could be rendered normally for the server output. Only a few templates will need to be of dual purpose like that - the fragments that are to be replaced by the js.
I agree with Ignacio, it is much better to keep just one copy of each template, so that you don't have to write a separate one for the javascript, however there is definitely room for improvement from the approach that I've mentioned above.
Ideally you might want to have templates compiled into robust javascript function code as well as plain string for the output by the server.
Closure templates called Soy, solve the problem nicely but do not (perhaps just yet) work with python, but they do work with Java and Javascript. Hopefully one day there will be python support for that.
But even if that happens, the templating language will be probably more restricted as it will be tough to make things like .get_absolute_url(), filters, etc work both in python and javascript - all automatically.

Categories

Resources