Jade is an HTML preprocessor with lots of great features to speed up writing HTML. Sanjay walks through the basics along with a few advanced ...
🔥Getover600WebdevcoursesandbooksBrowseJavaScriptComputingDesign&UXHTML&CSSEntrepreneurWebPHPWordPressMobile
Jadeisaneleganttemplatingengine,primarilyusedforserver-sidetemplatinginNodeJS.Inplainwords,Jadegivesyouapowerfulnewwaytowritemarkup,withanumberofadvantagesoverplainHTML.
Forexample,takealookatthismoviecardinHTML:
Ocean'sEleven
DannyOceanandhiselevenaccomplicesplantorob
threeLasVegascasinossimultaneously.
ThisiswhatthesamemarkuplookslikeinJade:
div
h1Ocean'sEleven
ul
liComedy
liThriller
p.
DannyOceanandhiselevenaccomplicesplantorob
threeLasVegascasinossimultaneously.
TheJadeversioniselegantandconcise.Butit’snotjustaboutthebeautifulsyntax.Jadehassomereallyneatfeatures,allowingyoutowritemodularandreusablemarkup.Beforewegetintothesepowerfulfeatures,let’sdoaquickoverviewofthebasics.
TheBasics
I’mgoingtohighlightthreebasicfeaturesinJade
Simpletags
Addingattributestothetags
Blocksoftext
Ifyouwanttotrythisoutaswegoalong,youcanuseCodePenandchooseJadeasyourHTMLpreprocessororusetheonlinecompilerontheofficialJadepagetocompileyourJadetoHTML.
SimpleTags
Asyoumighthavenoticedearlier,thereareno“closing”tagsinJade.Instead,Jadeusesindentation(i.e.whitespace)todeterminehowtagsarenested.
div
pHello!
pWorld!
Intheexampleabove,sincetheparagraphtagsareindented,theywillendupinsidethedivtag.Simple!
Jadecompilesthisaccuratelybytreatingthefirstwordoneachlineasatag,whilesubsequentwordsonthatlinearetreatedastextinsidethetag.
ViewthisexampleonCodePen
Attributes
Allthisisgreat,buthowdoweaddattributestoourtags?Quitesimplereally.Let’sgobacktoourfirstexampleandtossinsomeclassesandaposterimage.
div(class="movie-card",id="oceans-11")
h1(class="movie-title")Ocean's11
img(src="/img/oceans-11.png",class="movie-poster")
ul(class="genre-list")
liComedy
liThriller
Prettyneatright?
Ocean's11
Comedy
Thriller
ViewthisexampleonCodePen
Butitdoesn’tstophere.JadeprovidesspecialshorthandforIDsandclasses,furthersimplifyingourmarkupusingafamiliarnotation:
div.movie-card#oceans-11
h1.movie-titleOcean's11
img.movie-poster(src="/img/oceans-11.png")
ul.genre-list
liComedy
liThriller
ViewthisexampleonCodePen
Asyoucansee,Jadeusesthesamesyntaxasthatwhichwe’realreadyfamiliarwithwhenwritingCSSselectors,makingiteveneasiertospotclasses.
BlocksofText
Let’ssayyouhaveaparagraphtagandyouwanttoplacealargeblockoftextinit.JadetreatsthefirstwordofeverylineasanHTMLtag–sowhatdoyoudo?
Youmighthavenoticedaninnocentperiodinthefirstcodeexampleinthisarticle.Addingaperiod(fullstop)afteryourtagindicatesthateverythinginsidethattagistextandJadestopstreatingthefirstwordoneachlineasanHTMLtag.
div
pHowareyou?
p.
I'mfinethankyou.
Andyou?Iheardyoufellintoalake?
That'sratherunfortunate.Ihateitwhenmyshoesgetwet.
ViewthisexampleonCodePen
Andjusttodrivehomethepoint,ifIweretoremovetheperiodaftertheptaginthisexample,thecompiledHTMLwouldtreatthe“I”intheword“I’m”asanopeningtag(inthiscase,itwouldbethetag).
PowerfulFeatures
Nowthatwe’vecoveredthebasics,let’stakeapeekatsomepowerfulfeaturesthatwillmakeyourmarkupsmarter.We’lllookatthefollowingfeaturesinremainderofthistutorial:
Loops
JavaScript
Interpolation
Mixins
UsingJavaScriptinJade
JadeisimplementedwithJavaScript,soit’ssuper-easytouseJavaScriptinJade.Here’sanexample.
-varx=5;
div
ul
-for(vari=1;i<=x;i++){
liHello
-}
Whatdidwejustdohere?!Bystartingalinewithahyphen,weindicatetotheJadecompilerthatwewanttostartusingJavaScriptanditjustworksaswewouldexpect.Here’swhatyougetwhenyoucompiletheJadecodeabovetoHTML:
- Hello
- Hello
- Hello
- Hello
- Hello
ViewthisexampleonCodePen
Weuseahyphenwhenthecodedoesn’tdirectlyaddoutput.IfwewanttouseJavaScripttooutputsomethinginJade,weuse=.Let’stweakthecodeabovetoshowaserialnumber.
-varx=5;
div
ul
-for(vari=1;i<=x;i++){
li=i+".Hello"
-}
Andvoilà,wenowhaveserialnumbers:
- 1.Hello
- 2.Hello
- 3.Hello
- 4.Hello
- 5.Hello
ViewthisexampleonCodePen
Ofcourse,inthiscase,anorderedlistwouldbemuchmoreappropriate,butyougetthepoint.Now,ifyou’reworriedaboutXSSandHTMLescaping,readthedocsformoreinfo.
Loops
Jadeprovidesanexcellentloopingsyntaxsothatyoudon’tneedtoresorttoJavaScript.Let’sloopoveranarray:
-vardroids=["R2D2","C3PO","BB8"];
div
h1FamousDroidsfromStarWars
fornameindroids
div.card
h2=name
Andthiswillcompileasfollows:
FamousDroidsfromStarWars
R2D2
C3PO
BB8
ViewthisexampleonCodePen
Youcaniterateoverobjectsandusewhileloopstoo.Checkoutthedocsformore.
Interpolation
ItcangetannoyingtomixJavaScriptintotextlikethisp="Hithere,"+profileName+".Howareyoudoing?".DoesJadehaveanelegantsolutionforthis?Youbet.
-varprofileName="DannyOcean";
div
pHithere,#{profileName}.Howareyoudoing?
ViewthisexampleonCodePen
Isn’tthatneat?
Mixins
Mixinsarelikefunctions.Theytakeparametersasinputandgivemarkupasoutput.Mixinsaredefinedusingthemixinkeyword.
mixinthumbnail(imageName,caption)
div.thumbnail
img(src="/img/#{imageName}.jpg")
h4.image-caption=caption
Oncethemixinisdefined,youcancallthemixinwiththe+syntax.
+thumbnail("oceans-eleven","DannyOceanmakesanelevatorpitch.")
+thumbnail("pirates","IntroducingCaptainJackSparrow!")
WhichwilloutputHTMLlikethis:
DannyOceanmakesanelevatorpitch.
IntroducingCaptainJackSparrow!
PuttingItAllTogether
Let’sputtogethereverythingwe’velearnedsofar.Saywehaveanicearrayofmovies,witheachitemcontainingthemovie’stitle,thecast(asub-array),therating,thegenre,alinktotheIMDBpageandtheimagepathforthemovie’sposter.Thearraywilllooksomethinglikethis(whitespaceaddedforreadability):
-varmovieList=[
{
title:"Ocean'sEleven",
cast:["JuliaRoberts","GeorgeClooney","BradPitt","AndyGarcia"],
genres:["Comedy","Thriller"],
posterImage:"/img/oceans-eleven",
imdbURL:"http://www.imdb.com/title/tt0240772/",
rating:7
}
//etc...
];
Wehave10moviesandwewanttobuildnicemoviecardsforeachofthem.Initially,wedon’tplantousetheIMDBlink.Ifamovieisratedabove5,wegiveitathumbsup,otherwise,wegiveitathumbsdown.We’lluseallthenicefeaturesofJadetowritesomemodularcodetodothefollowing:
Createamixinforamoviecard
Iteratethroughthecastlistanddisplaytheactors.We’lldothesamewithgenres.
Checktheratinganddecidewhethertodisplayathumbsuporathumbsdown.
Iteratethroughthemovielistandusethemixintocreateonecardpermovie.
Solet’screatethemixinfirst.
mixinmovie-card(movie)
div.movie-card
h2.movie-title=movie.title
img.movie-poster(src=movie.posterImage)
h3Cast
ul.cast
eachactorinmovie.cast
li=actor
div.rating
ifmovie.rating>5
img(src="img/thumbs-up")
else
img(src="img/thumbs-down")
ul.genre
eachgenreinmovie.genres
li=genre
There’salotgoingonupthere,butI’msureitlooksfamiliar–we’vecoveredallthisinthistutorial.Now,wejustneedtouseourmixininaloop:
formovieinmovieList
+movie-card(movie)
That’sit.Isthatelegantorwhat?Here’sthefinalcode.
-varmovieList=[
{
title:"Ocean'sEleven",
cast:["JuliaRoberts","GeorgeClooney","BradPitt","AndyGarcia"],
genres:["Comedy","Thriller"],
posterImage:"/img/oceans-eleven",
imdbURL:"http://www.imdb.com/title/tt0240772/",
rating:9.2
},
{
title:"PiratesoftheCaribbean",
cast:["JohnnyDepp","KeiraKnightley","OrlandoBloom"],
genres:["Adventure","Comedy"],
posterImage:"/img/pirates-caribbean",
imdbURL:"http://www.imdb.com/title/tt0325980/",
rating:9.7
}
];
mixinmovie-card(movie)
div.movie-card
h2.movie-title=movie.title
img.movie-poster(src=movie.posterImage)
h3Cast
ul.cast
eachactorinmovie.cast
li=actor
div.rating
ifmovie.rating>5
img(src="img/thumbs-up")
else
img(src="img/thumbs-down")
ul.genre
eachgenreinmovie.genres
li=genre
formovieinmovieList
+movie-card(movie)
Andhere’sthecompiledHTML:
Ocean'sEleven
Cast
JuliaRoberts
GeorgeClooney
BradPitt
AndyGarcia
Comedy
Thriller
PiratesoftheCarribean
Cast
JohnnyDepp
KeiraKnightley
OrlandoBloom
Adventure
Comedy
Butwaitaminute.Whatifwenowwanttogotothemovie’sIMDBpagewhenweclickonamovie’stitle?Wecanaddoneline:a(href=movie.imdbURL)tothemixin.
mixinmovie-card(movie)
div.movie-card
a(href=movie.imdbURL)
h2.movie-title=movie.title
img.movie-poster(src=movie.posterImage)
h3Cast
ul.cast
eachactorinmovie.cast
li=actor
div.rating
ifmovie.rating>5
img(src="img/thumbs-up")
else
img(src="img/thumbs-down")
ul.genre
eachgenreinmovie.genres
li=genre
ViewthisexampleonCodePen
Conclusion
WewentfromknowingnothingaboutJadetobuildingsomebeautifulmodularmoviecards.There’salotmoretoJade,butI’veglossedoversomeconceptstokeepthingssimple.SoIhopethistutorialpiquedyourcuriositytolearnmore.
Importantnote:Assomeofyoumightalreadyknow,JadehasbeenrenamedtoPugduetoasoftwaretrademarkclaim.Inthefuture,articlesonJadewillusethenewname“Pug”or“PugJS”.
ShareThisArticleSanjayGuruprasadSanjaylovesarchitectingsystemsandrunsthewebandmobileteamatSoftrade.Healsolikestohackontinyvisualizationandmachinelearningprojects.Youcanlearnmoreabouthimandhisprojectsatsanjaypojo.com.jadejadehtmlLouisLUpNextAStep-by-StepTypeScriptTutorialforBeginnersJackFranklinGreenSockforBeginners:aWebAnimationTutorial(Part1)MariaAntoniettaPernaACSSMulti-columnLayoutTutorialforBeginnersBaljeetRathiIntegratingJadeTemplatesintoRailsforCleanerTemplatesHendraUziaUsingJadeandGrunttoSpeedUpHTMLProductionNouranMahmoudStudy:WhatErrorsDoBeginnersMakeLearningHTMLandCSS?LouisLazaris