Ajax & Template Engine - goshaQ/iu-practice-as GitHub Wiki
AJAX
Что такое AJAX?
AJAX («Asynchronous Javascript And Xml») – технология обращения к серверу без перезагрузки страницы. За счет этого уменьшается время отклика и веб-приложение по интерактивности больше напоминает десктоп. Несмотря на то, что в названии технологии присутствует буква X (от слова XML), использовать XML вовсе не обязательно. Под AJAX подразумевают любое общение с сервером без перезагрузки страницы, организованное при помощи JavaScript.
Что можно сделать при помощи AJAX?
Элементы интерфейса
В первую очередь AJAX полезен для форм и кнопок, связанных с элементарными действиями: добавить в корзину, подписаться, и т.п. Сейчас – в порядке вещей, что такие действия на сайтах осуществляются без перезагрузки страницы.
Динамическая подгрузка данных
Например, дерево, которое при раскрытии узла запрашивает данные у сервера.
Живой поиск
Живой поиск – классический пример использования AJAX, взятый на вооружение современными поисковыми системами. Пользователь начинает печатать поисковую фразу, а JavaScript предлагает возможные варианты, получая список самых вероятных дополнений с сервера.
Template engine
What Are JavaScript Templates?
JavaScript templates are a method of separating HTML structure from the content contained within. Templating systems generally introduce some new syntax but are usually very simple to work with, especially if we’ve used templating systems elsewhere previously (eg. Twig in PHP). A fun point to note is that token replacement is usually symbolized by double curly brackets ({{ ... }}), which Mustache and Handlebars derive their names from.
When should we use JavaScript Templates?
As soon as we find ourselves including HTML inside JavaScript strings we should be starting to think about what benefits JavaScript templates could give us. Separation of concerns is of utmost importance when building a maintainable codebase, so anything which can help us achieve this should be explored. In front-end web development this is epitomized when separating HTML from JavaScript (this works both ways in that we shouldn’t include JavaScript inline in HTML).
Some common scenarios which could benefit from JavaScript templates are real-time web apps (for example a live streaming app for event commentary), or internationalization (i18n), which will quite often require that different content is displayed using the same formatting.
How Do We Implement JavaScript Templates?
We’ll go into more detail on this with specific library examples, but essentially it’s as simple as including our chosen library, fetching our template and rendering it alongside some data.
Most libraries support both inline and external templates. Inline templates are great for when we’ve got very few templates or we know that we’ll be using the included templates on each page load, but generally our templates should be external. External templates bring many benefits, chiefly that templates will never be downloaded to the client unless they are needed by the page.
Top of JavaScript templating engines
Mustache
Mustache is one of the most widely known templating systems that works for a number of programming languages, including JavaScript, Node.js, PHP, and many others. Because Mustache is a logic-less templating engine, it can be literally used for any kind of development work. It works by expanding tags in a template using values provided in a hash or object. The name logic-less comes from the fact that Mustache works purely by using tags, all values are set and executed according to tags, so you end up saving yourself hours of ‘nasty’ development work.
Handlebars
Handlebars is a close successor to Mustache, and both can actually be used at the same time, with the ability to swap out tags where necessary. The only difference is that Handlebars is more focused on helping developers to create semantic templates, without having to involve all the confusion and time consumption.
doT
doT.js is small, efficient, fast and lightweight templating engine that supports itself (no dependancies), and works great with Node.js and native Browser integration
Dust
Dust.js comes from LinkedIn — a fully asynchronous Javascript templating system/engine for the browser and server. Dust, while not completely logic-less, does involve a lot less logic than your average templating system. With Dust you’re moving all your logical parts of the code towards a simple data model, at which point you’re able to execute functions within that model and call it forth by using the template system itself, which then grants you full control over how your templates react in different situations.
Template Engine for our project
I thought about Mustache and Handlebars. Let's think about difference between them.
Mustache pros:
- Very popular choice with a large, active community.
- Server side support in many languages, including Java.
- Logic-less templates do a great job of forcing you to separate presentation from logic.
- Clean syntax leads to templates that are easy to build, read, and maintain.
Mustache cons:
- A little too logic-less: basic tasks (e.g. label alternate rows with different CSS classes) are difficult.
- View logic is often pushed back to the server or implemented as a "lambda" (callable function).
- For lambdas to work on client and server, you must write them in JavaScript.
Handlebar pros:
- Logic-less templates do a great job of forcing you to separate presentation from logic.
- Clean syntax leads to templates that are easy to build, read, and maintain.
- Compiled rather than interpreted templates.
- Better support for paths than mustache (ie, reaching deep into a context object).
- Better support for global helpers than mustache.
Handlebar cons:
- Requires server-side JavaScript to render on the server.*
So, I chose Handlebar for our project.