
Danas se front-end razvoj više ne odnosi na izgradnju statičkih HTML oznaka i kompajliranje SASS datoteka. Porast aplikacija s jednom stranicom (SPA) znači da možemo učiniti puno logike prikazivanja na strani klijenta. Suvremeni web razvoj često zahtijeva dinamički unos podataka.
Iako je React.js sjajan, često zahtijeva krivulju učenja za programere prije nego što ga mogu integrirati u tim. Nedavno sam dobio zadatak da napravim internetsku stranicu tečaja. To je označilo početak mog istraživanja na Handlebars.js.
Upravljači su popularan i jednostavan mehanizam za izradu predložaka koji je jednostavan za upotrebu. Izgleda mnogo poput uobičajenog HTML-a, s ugrađenim izrazima upravljača u kovrčavim zagradama {{}}.
{{name}}
{{quote}}
Prije nego što prijeđemo na detalje upravljača, pogledajmo kako će se podaci umetnuti na stranicu putem vanilin Javascripta. Uzet ćemo primjer izrade web stranice koja sadrži nekoliko citata. Jer, hej, svima treba neka inspiracija.
Javascript od vanilije
Dohvat podataka
Većinu vremena možda dohvaćate podatke putem ajaxa, ali radi jednostavnosti stvorit ćemo vlastiti objekt podataka.
// quotes.js var quotes = [ {name: "Frank Lloyd Wright", quote: "You can use an eraser on the drafting table or a sledge hammer on the construction site."}, {name: "Douglas Adams", quote: "The major difference between a thing that might go wrong and a thing that cannot possibly go wrong is that when a thing that cannot possibly go wrong goes wrong it usually turns out to be impossible to get at or repair."}, {name: "Ettore Sottsass", quote: "I try and be as stupid as possible regarding my profession, which means I try to look at as few design magazines as possible."}, {name: "Shaun White", quote: "I’m a big fan of doing what you are really bad at. A lot."} ]
Stvaranje HTML oznake
// index.html
Dodavanje podataka pomoću Javascripta
Upotrijebit ćemo petlju for za petlju kroz gornji sadržaj.
//quotes.jslet quoteMarkup = '';
for (var i = 0; i < quotes.length; i++) { let name = quotes[i].name, quote = quotes[i].quote;
quoteMarkup += ' ' + '' + name + '
' + '' + quote + '
' ' '}
document.getElementById('quotes').innerHTML = quoteMarkup;
S ovakvim kodom teško je čitati i zamorno pisati. A HTML oznake za ovu stranicu sada se nalaze i u index.html i quotes.js.
Unesite upravljač
Početak rada
Za početak moramo uključiti datoteku izvornog koda upravljača. Vezu možete dodati unutar oznake head ili prije kraja.
Alternatively, you can also link to Handlebars from a CDN.
Create the template
We will still use the data object of quotes from the file above. We will sprinkle some Handlebars magic on the index.html file.
//index.html
{{#each this}} {{name}}
{{quote}} {{/each}}
- each: Iterates through the data
- this: Referencesto the current context.
- text/x-handlebars-template: To tell the browser not to execute the script as normal Javascript.
Compile the template with Handlebars
It only takes a few lines to compile the data with Handlebars. That is what I love about it. Even if someone on the team has not used Handlebars before, the script and markup are very simple for them to understand and pick up.
let content = document.getElementById('quotes'), src = document.getElementById('quotes-template').innerHTML, template = Handlebars.compile(src), html = template(quotes);
content.innerHTML = html;
- content: Returns the element into which you want to insert the compiled information.
- src: Retrieves the markup of the template.
- Handlebars.compile(src): Compiles the template in use. It will return a function that the data can be passed to so it can be be rendered.
- template(quotes): Compiles the data into the template.
- content.innerHTML: Renders the above to the DOM
You can view the project here.
Bonus
I used Handlebars for a multiple-templates website. I found myself writing the same ajax and Handlebars code multiple times. So, here are the two functions that I created to make my life easier.
Getting data from ajax with Javascript
function ajaxGet(url, callback) { let xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // console.log(xmlhttp.responseText); try { var data = JSON.parse(xmlhttp.responseText); } catch(err) { console.log(err.message +' Getting: ' + url); return; } callback(data); } };
xmlhttp.open("GET", url, true); xmlhttp.send();}
Function to run Handlebars
function runHandlebars(id, dataSrc, src) { if(document.getElementById(id) != null) { let content = document.getElementById(id); ajaxGet(dataSrc, function(data){ let source = document.getElementById(src).innerHTML, template = Handlebars.compile(source);
content.innerHTML = template(data); }); }}
With these two functions, I could run all my Handlebars code on a single Javascript file. It will look something like this.
runHandlebars('nav-sub-1', '/data/courses.json', 'nav-submenu-template');
runHandlebars('contributors', '/data/contributors.json', 'contributors-template');
Conclusion
My experience with Handlebars has been a positive one. In my project, I use it with gulp and metalsmith. Will I use it for other projects? My take is I prefer something like React or a full fledged static site generator like Jekyll. But in this case, when the team is more comfortable with HTML markup and it is a relatively simple website, Handlebars is a good choice.