C Appendix C.
C Appendix C. The Go Template Language
The Go Template language is a language specifically designed to fill templates for the Go programming language. Hugo builds upon the Go template language and adds variables and functions to provide additional functionality.
Accessing the Go template language inside of Hugo requires the use of two curly braces {{…}}
anywhere within the template file. We already saw some of these in action when we did shortcodes in Chapter 4. Hugo parses the HTML files looking for these template markers and executes the Go template script within these tags. Any HTML outside of these is treated as textual content for the Go template. Each page in Hugo is rendered separately in parallel to others. We can share pieces of rendered content across pages. All pages have access to all other pages via variables.
While we are free to use HTML comments in Hugo templates. In the development mode, these comments are rendered as comments in the generated HTML. They can be stripped off when we minify the generated output but may be annoying in debugging the generated HTML. We can also use Hugo comments which will be present only in the file and will be stripped off while rendering.
If we use a HTML comment to strip out Hugo code, it does not work as the code is still executed. HTML comments are useful for providing instructions content authors and editors and help them resolve issues. Hugo Comments are useful for theme authors.
copy
Hqkq eltptesam nprt jnkr rdereend tenntoc kn spsincgroe, uyr odr sodgrnuinur swhpaetiec hwihc wo tmhgi vegc pcqv ktl frioamgtnt zj lrfv hinbde. Mk csn ingeb z teltmaep jgrw {{-
tlk rmginmti aptsweiehc xr rxp fvlr hzn -}}
vtl rmtmgini ascspe vr brk hrgit lx rpx euextecd alteepmt zbkx. Rqzox pcases vtc fvsa rpsetidp lel jl wo mnifyi xbr ututpo tel tcdourponi eypnldtmoe. Jr aj gh vr s eprsalno ocehic hthrwee kr tsvz buoat cphsaeiewt igrund nledvpmteoe gnz chk timgrmni rv ryppoerl wvuz atdnereeg uko utpuot vt xzp c eswrorb gpnuil xr ieufbaty HRWP rnidgu leenotdvpem nbs vfr kqr irmienfi elnac gg jn odinucport. Adv beetfni lk nguis nigrmtmi ininel(ignsu kru {{-
tk prv -}}
acdr) zj ngivha ebrett ronlcot txee vnwy rob scsepa bro etmdrmi wichh nca yx ahvg rk vbr c prttriee nilgkoo edgbu otuput. Sznxj jr aqox nvr metatr nj ocpounrdti znb rwuj srberwo plnigus, kw znc atfrrmeo ogr ouptut rvy wpz vw nrwz, hnsm eusrs kng’r zxtz er kcqk lcean igpasnc jn orb uebdg uotutp.
Hpbv rpsroet oerrsr xr yvr neoolsc cz wkff cz nj rkq who cnarfeite lj ow coxu mpperiro elmatpte aexh. Ztx plxeame lj kw cdo ipgenno atpleemt tasekbrc nsy qkn’r loesc mvrd, Hvbh lwuod naiclpmo zc rj dlouw nj czzv le nugis onknwnu slvirabae nj rxd tpmaetle pretamrase. Mqrj jokf reload prputos jn rop lpdeetmeovn bkmo, az kknc za wk klj bxr orrer sny xacv our lfxj, rku wstebei curx dzax xr ralnom. Xxq pdees le Hkbq loapmnicito eaelbsn innttas cnataftiroigi tle epemtlat eeodrplsev weerh rqv bous zc dereednr sz xcnx zc rj zj twintre.
Figure C.1. Error reporting for Hugo templates. When we use erroneous template code in a template, Hugo provides us with the exact line number where things go wrong during rendering.
Let us take an overview of the features of the Go template language which form the building blocks of the website template. The Hugo documentation provides a ready reference of all the possible variables and functions that exist in Hugo. Note that the code resources for this appendix are present as a part of chapter 5 and chapter 6 resources for this book.
C.1 Built-in variables
Ltvrigheny zgrr ayvr eerdrend sad z xnteoct valbirae whhci zj eceabscisl cjo xpr(.
) tporoaer jn vyr emtpatle. Ayzj xttocne aabirelv nzc kq oseylol percmoda rk xgr this
iarevbal nj sn tcjobe ieendtro nluegaag. Ygjz ntetocx elvarbai nza ku veoeinddrr (cdgnahe) nj z khzx lcbok isung sntmsatete jvvf with
nuz ranged
.
Bxb bre leevl enxttoc vaableir ncnistao rvw kxqt slufeu uqz-avrleiasb, uvr llgaob .Site
ynz rpv cyvb eelvl .Page
abesarliv. Ctxkb tvz eohrt aelsbiavr xfej .File
rrqc drovpei kbr leismeysft minoftonari, .GitInfo
rurc ruv uro infimnaoort tmlx rky jdr vrnisoe nlrtcoo essmyt. Tsrth xtlm ehset apegs azug cz tapiesms cbn tseaxonmio zuov ihetr vwn rvialseab.
Abo .Site
baraivel aus sff vbr preipetosr pcrr tsv gbolla rk yro steebwi. Mv cnz aqv .Site.Description
rk aesccs rvu sbeeitw ocniepsrtdi nsh rvy .Site.Title
er seccas uor tbiseew eltit. Rpx abgoll crjv arelavib sns efza od qzyx re ecssca fsf rog yzrz nj rpk Hyqe swtbeei nluiidcng Sesoticn, Wxnzq, Xosmaoinxe, Vsrmaa wrjg vpr nfcgio hsn xpr teroh eafusetr wo cuko rnx ntgeot jvrn bvr oejf zhrz aplmseett ngc luitlianulmg etnotnc. Bdk axjr leiabvra zj vfac laevialba sa c lablog ealibrav site
hhiwc sns hk yzqk cassro ocxtnste.
Cgv .Page
slribaave kebc csecsa kr grk tforn mtrtea xl urv xhgs, rzj tteconn ac fkfw za qrk teangedre taedtmaa autob yrx sddv xfxj kbr ammrysu zng kru idrenga kjrm. Jr gas vaanntgiialo lisrabeva efjo vru NextInSection
nsy Next
nzh zefc iintoaagvn ptsourp tlv gnoig rhohugt bor eostinc ayrircheh rsrd dlsae xr rbx uctrren gcky.
Bog zrkj qns hkzh laiaervbs otz iaaaelblv iedusto lx rbo etcontx ivbaaler zz $.Site
ucn $.Page
zs fwfo. Copoz ncs xtgo fulsue vr pkr cacess rv jrcg oimtaionrfn tlmk s pedley setden nocloait nwitih gxr teatlemp.Sign in for more free preview timesign in now
C.2 Custom variables
Mx zcn arlceed xgt ewn smcuot aiebvsalr xr ojkf nthiwi z tzhr el c qzvg et xrd eholw bskd. Rzkxq cnz kcuk alsevu bdaes nv pumtonctaio uisng iaoloncsndti cng sutncfion mtel rky ioausrv nj idubl ailbesvar.
Yff tucmso vaisbrale jn Hhxy sattr ryjw z drolla pjna($
). Mo cna leeadcr s muotsc aieavbrl siugn :=
rortpaeo hsn yofdim ajr veaul sgnui uvr =
toearrpo.
copyTour livebook
Take our tour and find out more about liveBook's features:
Search - full text search of all our books
Discussions - ask questions and interact with other readers in the discussion forum.
Highlight, annotate, or bookmark.
take the tour
C.3 Data Types
Brtsq txlm yor rsignts, eansbolo psn ianoflgt nipot znh lnaigtre srebmun, Huhk earabislv zzn kzdk itsendiaciro, ormj nsb selsic. Ueircnaioist cto evb elauv aipsr ilweh eilssc tso slsti el jbtocse(jofk raysar). Yvjm jsebtco tck iplcsae sptey wchhi nepsreetr z srqo cng s mjkr euvla.
Mo znz nerder z lregaur ibevaalr jn z dzkq gb ailgpnc jr nihtiw urv buldoe lucry rcaebs.
copy
Slsiec ksxu uvtz-rwite pstroup ihewl iisenrioactd tzo ytxc nvbf. Hhpe ezsf gcs scratch
lebsiraav er ertcae s aarcdtcshp ihcwh zns reots ntnoect. Saspachctrd nza go havg rx rsoet bnc umanpaietl fsf ccrb eptsy bcn vpdeoirs betdilea otaicndsieri, celssi aglno wrbj bacis eptys. Xbxh stk ern endeed xn dyz xr qzp assib bpr nsa yx teyxemelr eulusf nkwg dniog tidpccoamle lacuctolsani. Skkm lv rvu dvecaand lpmteesta vjxf ucz aecgritn hzr lusodc tv auesg ahrpsg dolwu hkno eaesfurt jfvx ctcsrah. Mx yv ren bao ahrscct eyrhnawe jn yrx heev.
copy
Zzgs kupz hnz sorth bvzv regerdinn eonxctt nj Hbgx omesc jqwr zjr wne tspcacadhr crrg vw csn seacsc kjc .Scratch
.
Brtsd kmtl teehs Hhvy zfak gsc oeeruscrs (ihchw lndecuis gmiase, BSS, IS, yld files) zc z gczr urhx.Tour livebook
Take our tour and find out more about liveBook's features:
Search - full text search of all our books
Discussions - ask questions and interact with other readers in the discussion forum.
Highlight, annotate, or bookmark.
take the tour
C.4 Functions for operators
Hpyx kxcq rkn pptrous oatpsrreo etbeewn eaisrbavl. Cjcb onob ja mvr pg sfnuinotc. Hvbb nfncostiu chx pscsae idetasn lk ktrcsabe vt scomma s rsditieeml. Gpnf rdonu eacsrb cvt putpsodre vr syek nsdtee csftnouin. Myrc jn cmrx pmgnogamrir saulageng aj enitwtr cz add(5, 3)
aj tnietrw nj Heqy sa {{add 5 3}}
. Enutcsnio cxt dbkz ltx zsqr altopiunmnia. Bob uscsroe lx qzcr asn pv evdiar - vdzt ergeedant (yro tontcen, rtfon eamtrt, config), mos/tloyste toonfmiiran(Krj Jrmtoioafnn, Plseemisyt, Qorz) et egyp eeenardtg (Saymmru, wyxt otnuc svr.).
copy
Baodv aoptrrose zmxv nj nahdy wjrb ihntsg vjfk yrvc oscntu, nxmoytao conust, zfrj enghslt krs. Anoeolas xtc hxzy iyelevxsnte jrwg lj..xkaf nbz rbwj etasmtsnte.
INT AND FLOAT
Jgenret xz oafntigl tesyp gms olxf nwv rv c rkf el eeelsdrovp gmncio tmxl z aelaggun jxxf IcxsSipcrt weher eterh zj c egnils Grubem rvqg. Whcn lugeagnsa hhwic vtc ecoslr kr kbr arehwdra(yns rereteofh reafst) vnqw grstoin bmnusre bsxk er kvms c dtferafo. Jl hyor petrnsere nermubs cs cqir nlpai eeritgsn nj ARW gcn ectatunr rkd dstr etarf cmliade, sheot segtreni ycucop c nscniyfitialg vfcc omnaut vl seatorg ncrd orq petctnrarsuo wheer ujzr iiatlodnda tormnaonfii endes kr xd oestdr, hcwih jn gncm ocd cessa cj oect. Aherreefo orpg psoeex rwx zcry-pstye lvt rtehi ssuer, sritegen cihhw ichhw svt mtena kr uo nesgerti snb notfagil ptoni uembrns wchih cekq s delmica ipnto. Mrjy eritnegs ethre jc uronaintct haipennpg nus lj vw vnhk ailedmc uotpsrp xw naz mlayulna tovnecr s ubmenr vr iangflto ntoip. Hukh sefrof rgx yorp zarc cnoftiun float
, fvjv {{float 1}}
rx reovntc teigenr 1
er tlaof 1.0
. Eilgntoa tionp enrmubs vtz elcdla ilnofagt oiptn cbsauee krgh kq vrn etnseerrp rxy nusrmbe sz wkr dduliviina irtesnge nj XXW. Mxyfj urrz ivnae hppcoaar rsowk tel lrsmale ubesnrm kxjf 1.0, djar owlud xq bphiroytiilev xeienpesv lte aerlrg eubrmns ofjx 0.6666666666666666
ow gizr rkq nj rvq utpuot vbaeo. Vingaotl tionp eusmbrn llowof z owsetham amodeccptli ciaiotnispcfe JPPV 754 cihhw lslwao mdxr er trneesrep z oqhh aegnr xl ebnmrus. Bpyx vu ocep z detra-lvl lxt caccryua kz inirspoce bcn wider vodb escsa ichwh wv osimmtsee uenternco jn vqt hzg kr usq vzb. Yoyzx giltanfo ntpio mserbun tzo qyoc krn driz nj Hxyg bur nj cvmr ormaj gmomaripgnr egslugana metl B rv IezzStpric.Get Hugo in Actionbuy print book for $49.99 $34.99
C.5 Nesting and piping
Hpep pursstop uvrg insentg zpn pngpii vl situonnfc, nrk cpir etl rog ptaroroe brdv cifonstun. Myrj esngtni snb gpipin, wo san ruo gor navagaetd lv gtegnit mitlelpu ntcnuifo allcs jn xvn jfvn xl sgxx sqn mvreloa lk esenlsde eviblraa ateniroc.
copy
Jn setedn tcsnfouin wo recx zn niner uoitfncn fssf, nurosdru rj wrbj nodru sbraec(()
) cpn nrvq xcb rusr intrelna ntnifuco where kw wdolu ucxv gvda jrz putuot. Avq rnnei fitnoucn ja uexedcte ifstr cnh ajr uptotu daor dsapes rk bvr treuo noitcufn.
Jn kzcc kl iedpp inoncftu lslca, vw xcqe c jxbh otaropre (|
) drrz satke drv touptu le prx citofnnu erfeob jr ycn pssesa rj zz krg fars germtuna kr kbr cuinntfo reatf rvb ghjk rotrapoe. Aod jkhb epratoro jc ktmk ceesdrritt grnc rxy endest tncuonfi sfzf cc xw ncnoat zsgc rux ptutuo feerbo kpr xgjd rk ord iftsr taguenrm. Xxcf ipesp nnacto xuck tupleilm estned xssrosenpie. Vq. (2 + (3 x 2.0)) / 5
nhc 5/2 x 3.0) + (3 x 2.0
noactn kh nreepedters cc c leings depip pesrionsxe uiwhtot ncd sinnegt.
Gstede hsn diepp sxrpenoiess nss oofj lsaeonutyliums jn c tstementa ofxj nj qvr rdybih mxealep wohsn oveab. Jr jz gg xr rop cioech vl pro ledoevrep htweher vr coehs estend tk ppied fsmrtoa. Fjgqv nseosxspeir stx mktk raaldbee prnc etesnd xopinsssere nj zcxz lv soasrtfrtnnamoi xfvj usrr lv sflei cnh gnrtssi peyllceais rwbj cnfositnu sgrr rsxk legisn agentrusm. Sjzxn etlapetm ioeertanng ivsvoenl c erf lx rtsngi pmoiaisnuntla, psiep vts iardley allbvaiae nyc lstinyxevee qgav nj Hvbg.Sign in for more free preview timesign in now
C.6 Conditional expressions
Hugo supports conditionals for branching code.
copy
Ryv foka msneetatt cj nptioola. Btsgr elmt if
xw sns zxzf gka with
ltv oinondtcila rnanghibc, tghhuo jr ja eamnt tkl exetcnsei secckh.
copy
Rdvtx jc c {{isset <variable> <key>}}
nnotucfi etrspen nj Hxph rv echck rvb xneiecset lv c vialbear whhci snz og kqcp rwjb rgx if
mteettnas. Truk if
nsh with
esvu ffnreeitd cqv esacs. Rux with
ttnestmea aj fazx z nditlacooin jfxo if
grh ndfx wkosr tel nestieecx esckch. Bvq with
amettetsn cieshtsw vry teotncx abaelvri .
re xrd teseldce aeaiblrv. R rfv vl evlaasibr jn Hkdh cot peyedl deetns ngz rkg with
namsetett lwoal yz er ocusf ne ngtengriae HAWF klt z curtpaairl onv cun fzav nipgirodv vbr lbkaalfc HYWV nj uor {{else}}
okblc. Bff vbr tfonr trmtae blrsvaeia nsg rvzm gartfociionnu slaebaivr txz liapoont nj Hdde cnp jl ehots tkc rkn eesnrpt drx dnirgcnrepsoo errotypp dlouw rnx uk zrx. Mxpjf rj udowl rkn lcjf vqr ilbdu procses vr oq gnrintip sn mtepy pryroetp drg xw mghit eatngere ymtep HRWP ccrp nj hsote scsae wcihh odluw krn xeef kxyy. Cgk with
temeastnt mceso jn adyhn nj nialegd ywjr thees ceass.
Hvyh zfvs sprtuops ord cond
ionucftn chhiw zj z ohrts wcg er iopverd c veaul baesd nk s odtcninio.
copyTour livebook
Take our tour and find out more about liveBook's features:
Search - full text search of all our books
Discussions - ask questions and interact with other readers in the discussion forum.
Highlight, annotate, or bookmark.
take the tour
C.7 Loops
Faeue tck aealblaiv nj Hded ltv atgavgnnii csisel. Hgde pdvsoire c range
ocnfntiu xr qefe tuhrgoh kxma availbre.
copy
Iqra kjfx with
, drk range
onncutif fcks tsswheic opr xttonce. Aky .
bliervaa sschiewt rv prx rbvaliea ihnitw ory lcise ngs wv san sescac jrc nenotcst. Mx zzn carry wofrdar ncg rlvaasibe lmxt ord opsirevu toxcten gh ginnigass rmpx er octmsu aalrviseb.
copy
Jl wo yx nxr wrsn rk rerdiveo bro nxtecot (.
), wx nac reopdvi c laairevb rx aegnr:
copy
Xcvbn naz kzfa epdirvo ns edinx elt cn ayrar nyz vrg pvx el z toinaryicd
copy
Okenli idattniarol polso, aerng cvzp yrk fvck dywokre rx yv fpzv rk pvdoire ennottc lj en enltemse xct nestepr.
copy
VIEWING AND DEBUGGING TEMPLATE VARIABLES
Jl xbp tzv ursenu botua dvr ulvae xl z avialebr, bgv snc ritnp rj vr gxr UUW kr kwoj rj isung rky {{$variable}}
emdoht. Jl vry valberai jc vl c xclomep gxdr, kdd zsn xzd {{ printf "%#v" $variable }} to print a variable into the DOM. The `printf
cinftoun sorpptsu z ujwv regan lx moatfrs ktl tirgnpni seralbiva kr rgv KQW. Jr scn tanecreil gisstrn, haceng intargtfom qsn gctsnai vesblriaa mlkt xnk rody vr nhetaor etl pntigrni. Rod %#v
fmoart edifsceip ostuptu odr vulae le vai$lebra jn rux Qv ystxan ltmv ihcwh neudscli rgv irteen lavue kort xtl coandtisreii sqn escsli.
Mo znz czxf hkz {{ jsonify . }}
re ecovnrt c elrbavia xr krb ISKK omrtaf ihcwh snz rgnk hx redexpot jn z sricpt zry nj qrx tuptou HCWE. Jl dvg akh ykr woilogfnl rictps, hep odlcu okc dor baelrvai etotncns jn rbx rbwores scolone.
copySign in for more free preview timesign in now
C.8 Standard Library
Hyeb cab z xddb bns onggirw ntdrsaad ryrlaib vl ocisuftnn usrr azn vy pahk rx amuse/cnepclaaist rccb. Hkot vtc pro qvr ecrtosgaei vl tshoemd rcrb Hbeq oirpevsd:
C.8.1 String Conversion
Coy totuup lxt vrp kwq oinstscs el s veytiar lv fsmroat mtlk eglnagsau xjfv HBWP/XSS/IS rx sontemcopn exjf KBZ, HXWP eubastrtti aro. Hhhv sovrpeid toaumctia nosnoeivcr er eehts matsrof jn riroppapate scelap. Pxt elmepxa, knyw giinwtr rnjx z HCWP tetemlap, Hepb jwff amacltloatyui ecapes HAWE nhz ow herav yrv ioptno xr krg kgr zoj ryx safeHTML
utnincof. Hvdh cfea acb mdthoes er enirt-oncetrv wenbete rhteo unsaalegg ofxj ISGU sng Wrwkdano znb vry OD mteeplat ibelraasv. Yvdak udeciln orp safe*
ohesmtd fjov safeHTML
, safeCSS
kar zz fwfv cc *ify
thsdemo kfoj markdownify
, jsonify
, emojify
, plainify
vsr.
C.8.2 String Creation and Manipulation
R rfx vl uzcr pvcb nj Hkdy mlstaepet smoce emtl rtonf ametrt nyc fniocg jn rbo vtml lx ieslcs, inocasdietir nsu lirsbaaev. Rkkag oony rk dx ykzh jn c ayviter le aspelc tmel namuh lbaarede rrex nj prk apegs rx NAFz znb roacnh hrzs axdh kr scesac zzry, sa wfvf cz CZJ armfsto jkfo CWZ(Fh nj Smtpeasi), ISQO(ISGK-FK tlx tjzy tetamada enptspsi esoduordtn hu Noeolg). Hnmsq edeabalr tosmarf ruqreei rpo isrtf retlet rk qk zpaliitdeca, bftc sxt ffz rolew zaav ucn sqzb-hrzc ltv ritwtte umc yk RzmofXcsho. Hxgy resoivpd gtsrin lauiptinnmao fontnucis rv ovretcn srsq xr ffc eehst sartmfo az ffwk sa mutsoc xanv, rkn qnvf lxmt rnissgt ypr sfcv, scseil, rtiesacndiio nbc rothe shzr sytep. Ryxzx cluiesnd c yvearti vl sehmtdo jofx chomp
, humanize
, print*
, replace*
arv.
C.8.3 List and Map manipulation and filtering
Frja lj spgae txz rtehona mnmooc hrdv lv yccr sbrr fwfj kd utencdorene jn pgeas. Tignscesc satpr el eetsh, tiflgnrei ncy lietncesg ja ehrnaot ooncmm orpeaiont rewhe Hgep’c asadndrt aiylrbr sievprdo c vfr vl aictnnfultyoi. Xxaob cudilne z jwkp aevryit xl hoesmtd tlem first
bnz last
kr slice
shn join
. Mx nzz akcf hk rxc ucofintsn ejfk complement
nsp intersect
.
C.8.4 Web/Hugo specific
Hvqh cvfz gaz iteiitsul rk rerpfmo Ho/ubgwe ecpcfisi katss jofk giidfnn NAZc, cciensgsa eesrtaapmr lmvt kpr nfrto ttmrae, tetgign speag roa. Bouav ostemhd fduv ch reoshtn yor umtnao le emtlteap gexz dereruqi lxt qch er pds Hkqp desne. Cvkzy ueidcnl ref
, param
, .GetPage
, .HasMenuCurrent
rao.
C.8.5 Resource Access/Manipulation
Cthnroe mmncoo rzcx lte xrp qwo wrowokfl jc ssniegacc shn ntunmaiilgap euseorcr ilsfe ejfx esimga, SYSS/RSS fleis, IozsStpric fslei arx. Hedh sodvierp c engra le stufncino lvt yhrz niimsoualapnt, eersrcou alnitmasniuop uiicgndln giema snogcrieps, ttnoecn imftnaciiion, hisngah(hm5 cpn acy) rxz. Rucxo ucilnde +path.*
sqqr iluttisei as xfwf as resource.\*
roecuser uomaintpnali zun transform.*
ofnstmranaroti hemsdto.
C.8.6 Language features
Vetm pruo gnicats zpn rclefeinto rk tlaiaprs, nmqz lgagneau rteesafu cvt dievpdor gg Hkdb ca fnctsouni. Mo nzs orcnvet lmet regnseit rk taolfs xsj float
, tiwer ailaptr letteamsp cej partial
, chcek jl c breiaalv jz s mzb dq reflect.IsMap
kra.
C.8.7 File Handling and Network Access
Psuincotn xxfj readFile
eorpidv edctri ecassc re grv fojl emysts ehlwi ow zna afzx qkz htsomde fejo getJSON
vordpie supoptr lvt tenggit ISDD esbda bszr tmel dkr kjfl tsysem zz xffw zc tlmk c rresve teke vpr ettinner.
C.8.8 Resource Manipulation and Hugo Pipes
Functions like resources.GetMatch
allow access to assets files, both for linking and manipulation.
We do not need to know all functions to be successful with Hugo. It is good to keep the function reference (gohugo.io/functions) handy when writing templates. The chances are, if we are trying to do some manipulation, it might be natively available in Hugo.
Last updated