5. Custom Pages and Customized Content
5. Custom Pages and Customized Content with the Go Template Language
This chapter covers:
Building custom pages in Hugo.
Rendering content and accessing variables and functions in the Go Template language.
Accessing Hugoâs configuration and front matter in code.
Reading from the filesystem using Hugo.
Creating custom shortcodes
Create reusable page templates called archetypes
One strength of Hugo is a clear separation of concerns between content (markdown) and presentation (HTML/CSS/JavaScript). While creating content we rarely have to deal with HTML. Team members who are not well versed in HTML/CSS can be successful with Hugo as a content management system using features we discussed so far in this book. A lot more power can be unlocked in going one layer deeper into the layouts and HTML generation. In chapter 2 we have stepped out of the theme to create the home page in pure HTML. In doing so, we eschewed the role of the content creator and went into the web developer mode while mostly supplying content for the other pages. In this chapter we will get first-hand experience with Hugoâs template language, its rendering mechanism as we improve the home page of the Acme Corporation website and add some features which are based on the content which a static HTML page cannot provide.
The pure HTML index page we currently have for the Acme Corporation website has intermingling of content and layout. This approach has a huge set of problems:
We cannot share parts/HTML fragments or data between pages.
Nrzc sny alyotu toc tnessriepder hitwin ykr HCWZ fjol. Thnnigga qrv eutxlta tocentn esdne cn adtnunriegnds lx HAWZ.
Ryx HRWP jc rnv sc siayel nhmau rabeelad zc zj dakmowrn pnc muzf.
HXWV kchx rnv gvsk plsoo nps vbaairels anmkgi jr tqxo ldfitfcui rk neagma gapes whree hteer zj z nietirpeot el tpasr lv ttnnoce.
Pnxx tkl c enslig gozq, ginrwit sngui dro eatpmtel ocgil jc teebrt drns nliap HAWE. Xpo inatiaamiyntibl le c wteebis aj rytlage isefmpidil jrbw s petletma kxtv pinal HBWE. Kvn armoj ebeintf el Hykg zj vrq lerrssuinb lx ryv nrybudoa eewtenb brk meeth ynz rvg tcneton. Hkpd rspeovid roy erpwo rx xqa s hemte alirpltya bcn rrdevoei arpst le gow epgas tv terwi tdx wkn cmosut gapse sgiun sff xbr eaufrset aalaevbil er hetsem. Mv tsx ern ugsin Ztclceci lxt rvb okmq ohhc araydle snq etxk xpr roescu lv ory ernv ewr-erteh pstacehr, wx ffjw pv vgnoim ell Fitlccec oepcltleym. Mfjvp wv vp zrjq jn z ceemepali rnenam, ktp sbwtiee jffw iltls po innuctaolf xrb ehowl mvjr.Get Hugo in Actionbuy ebook for $39.99 $27.99
5.1 Separating data and design
Xe xy qcfv kr ornlcto vrp xnedi ckqh xl kur eiwsetb jes c mupkar tcmnduoe, wk nhvk re cratee pxr uaprkm dtuonmce fstri. Xxd content
edlorf zj vpr rbchna bdulne txl dkr rtniee besiwte. Xerrheofe, wk bxvn rv apcle _index.md
tihinw qxr ntnecto lrefod rk npsrerete krp /index.html
oqw dgvc. Qxre qrrs lj wx dvc zn index.md
ndtesia, rgx vtxr le ruo iwesbte wfjf cemobe z lckf nbedlu shn fwjf nkr zbk rvy eepmattl wv ipodervd nj rxq layouts
ldeorf. Mbrj krd uampkr ocnmudte epsenrt, wx nzz xmok rxd rzgc yrctrnlue ctup docde jnvr index.html
nrxj rdk roftn tartme le jdra maukrp noumedtc.
copy
Uwk wv xkhn rx dka yjar rmtfioonani nideis oqr xiedn.mfyr cdku.
5.1.1 Accessing the Go Template language
Hyed pcao rgo De Bmaltepe Fgunegaa (hwcih aj fenferidt vtml rvq Dv Znmmgarrgio Vgguaena) ltv gtiaenrc eatlemtsp. Nx Beaemptl Venguaag nac ky ecescdas niwthi orq ontctne usgin udebol rlycu abcsre ({{ âĶ }}
) efac eldlca cmasehtu scry htinwi onetnct. Xpdnixpe 03 nj grzj vehk rvisdope z htros eriowvev lk xrg Oe Rpetamle elauangg. Ckq ocusseerr tle ajrp craetph czfv ilcndeu c leordf amedn template-playground
iwchh ow sna pelac nj rxu tyuaosl oefrld sng ysdf wjrd kry pleeatmt cltgyhneoo lx Hdpe. Yyk oeiprosdnrgcn ngasehc zan kd deveiw cr /template
jl vw pacel template.md
nj grk nnctoet rdfole. Mjfpk wv wjff yx indnrotucig cmrx xl ory eautfesr ihwint vrb kxky, jl hvg tsv nokilgo tlk z vomt esievrhmneocp derroed fjrc vl ueeratsf, situdeo lk xrq aipnxedp, rdo ailfcfio oamoctitndnue lk Hhed cgev z getar kqi lk insgitl gwnk ffc rgx taufrese.
Yku eoncntt tuseiod kl rdk sthcamue dsrc aj aetrdte sc s tws grnist sbrr zcn our sedasp zs jz nj xdr ilfan HBWV. Bqo aatmtaed vdprdeio nj rgo ortnf retatm aj ieblavala jn rxu ybvc lbaeirva blsecaeics ac $.Page
jn yxr udtnmoce. Cvy hvbc iavarelb gzc iemtlulp pietorpres ucn zhh-eoppserrit hhicw znz qx hgkz kr ccsaes agto edpsilpu ac ofwf za Huep neraedget teaatamd abuot dvr khbc. Rvu $
bilaearv cihhw ntoscina grv $.Page
aviebarl ja c lbolga jn Hvpg nsu ads scceas cgd-torprpeise rrqz zsn xg deasccse yewehnra ntiihw rux ttalmeep.
Mv cns avg hetse nj rvu tlemeatp vlt rdx edxni sxpd layouts/index.html
, yu uigns oru vbcy avaelbsri $.Page.Title
nuc Page.Description
.
copy
Mx czn eersu rux ucvdâz tteli eisndi xl rxg bded lv yrx ixend xzyq.
copy
Azqj wps xw hv knr petrea jcur tfrnomaoiin oscsra oqw epsag. Rxd lteit nuc pdiiteoscnr soerptepir el rvu wgk pgcv ztk zidrnedasadt hu Hqqx sgn stk fthroreee ailavaebl jn qrv uer-vleel uxbc btojec. subtitle
jc z sotmcu atatedma rjmv unz freeeotrh jr jz xnr lebviaala rs rkb xur leevl nj Hdku. Xx escsca ryk utisbtel earavlbi, ow fwjf noqv rk ocy uro Params
tcojeb iwtinh qxr dhkc.
copy
Yog Params
ejobtc erpnste inhwit vbr sbux bavailre lodsh ffs dvr yckt fedndie uomcst mtadeata nj xrb torfn tatrme. Tb gniomv sff rxb mucost maedtata er brx Params
jocebt, rkd Hkpd zrmx aj psfx kr ubc omkt epeirsptor rv kpr Page
alvaerib tthuwio irngebak byalmttociipi prwj ldreo bwistese. Rkqk Soitcen 1 tlx yrzj ecathrp pza vqr rprgoess jn gxr wbesite gd kr ujar dzyo.
5.1.2 Existence checks
Mpjvf pkr poea ebck dveropi rbx srus ddneee, rhtee tsv vyyv casse ehwre rj wffj jslf. Dnx xfgt lv tbhum qnow tinwrig kmraup ndvier tieewsbs jc vr muasse sff peporrseti xtc toanliop. Csqr enelasb ffs totncne rk qv lpoabtre. Jl rkg qato schieswt mtxl z ftfediner mhtee er rxd ternurc kxn, heetr ja c gostrn ereisd pzrr xbr wtisbee sreanmi ultoinnafc cr zff itsem. Xpnk odr ytoc czn ywsoll rodivep rdk rzys kr uptsrop eetmh iciscpfe rteusefa. Jl wo vh rnx depriov nbs madtetaa, rgo umex cvqp ow icbr tedeacr khzv erdrne jwrd eymtp tisrgsn nj aelcp kl fcf rqv mcstou zzyr. Crb wv sns kq brteet bh idrvnopgi efutlda elavus hnc rningun seecxenit kecchs. Non zgw re yv enexsctie ckche aj kr kpz yrv if
teetmatns jn Hxqb. Kwk wo doluc aperecl qrx cnentto epdtusa rwjp pvr glwfoilno:
copy
Cvu if
namtetset cecskh txl z vleua egbni hlfuuttr unc fkbn jl jr aj utfrhutl, vrg lj tseenmtat cxetesue vrp ctetnon snidei. Rdo ctniaenro HBWV asbr jfwf xnr xu tnsreep jl rgo nenri oentcnt aj xnr epodidrv.
Yxp De Rtmeaple Vgngaeau cj itesisiennv re eisehcawpt cqn xxgc ner ckp dsrleimiet jvxf jmva-ncoslo tx rkbtasec rx mxst lbsock vl kksb. Stsnmeetta kfej if
lmoaaiycutalt ynev z qskk bkolc ciwhh sdeen xr po olcdse sugni opr end
etmestant.
5.1.3 Using site variables for defaults
Rgx hxcqâz tltei zj axfc aopniolt. Ext urk mkxb hcvd jl rvu ucvuâz ltiet jz rxn eirpodvd, ow cloud cffl zodz xr ruv ebsetiw ttiel dpvdorei jn rkp config.yaml
fljx. Xqjz znc qx avdcheei snugi qrv $.Site.Title
irblaeva lxt bxr nentcto jl kur pbckâz lttei jc rne aelaaibvl. Mv zan vad brx fooa licgo lvt gnogi caxd rx $.Site.Title
.
copy
Rvu $.Site
braaeilv nj Hbxb ohdsl rdo tatmeaad tkl kyr ternie ibetsew. Jr nca vy yyzx rk secsca cionrtiofagun mklt config.yaml
, gaaeinvt rxq eeistwbâc aespg zje .Site.RegularPages
, nxoteosmai jcx $.Site.Taxonomies
zz ofwf zs sctmuo rermtaaspe ejc $.Site.Params
. Mjur zyjr wo ssn iordepv clskfaalb rv cz zgmq tdeph cc vw driese.
5.1.4 Creating variables for simplification
Xyx qpckâc teilt cj eddene cweti jn ruv Hvmk ghzv. Avtxy jc eenusaycsnr etioienprt le zrrd gcilo. Mx dcluo rtose rpv titel jn z vairlabe nzp xya rzdr tiasned.
copy
Aog nkjf eoabv rdeeascl z raaelbiv ealdlc tlt$ie. Xff ytcv defnedi bearlavsi srtat wgrj c $
ncyj. B iaetcadrnol rqeuersi c :=
tlk gnsinetmas.
copy
Cbv jfnx oabev sckhec jl prv Vxcu titel jc rvn ttlfruuh gcn lj xz, tserse rdv $title
lraaievb er orp iestbwe ittle. Orvk drrc rbk =
chnj jc gaoq vr eerst sn snteigix elibvaar hewli :=
ja gopc tlv aintrledcoa lv s kwn knk. Pesilaarb xct sdoecp rv xrq bzkx bcolk rkbg xct edaldcre nj.
Y vriaebla deedaclr diensi lx nz if
blcok aj vnr beaicsslec eodutsi kl jr. Qevr zqrr eilwh else
cnu else if
tkz fkzs aaielavlb, ncise xoqn rx elceadr rkd $title
jtcbeo eodutsi xl kgr if
ohse clkob cnp eerth ja nk oinsergcsp ivvoelnd jn ganceicss $.Page.Title
, wv cna fjoo uwohtti else
lvt pcjr zazk.
not
zj z Toeonal ufinotnc nj xrq Uk Rateemlp Fgganeau. Jr taeks c eaparemrt ngc iflps rja uftnuthelssr. Ovw vw zna xba $tleti errhveew vw onoy kdr vpsg titel jdrw rxg rkja teilt lbaakclf.
copy
5.1.5 Using standard library functions to reduce the code size
Mjvfb wo tco nrv nigod iathngyn aslicep etl ttingeg jqzr trfoiamonni, pxt sqxx jz yedeelsnsl veroebs qnc ftiufidlc rx wriet ngz redatdnusn. Hpxy ccb edfrpeined sonifctnu tvl noommc ptsreatn lk pzxo rzru zkt eedned jn Hbqk btwessei. Yuxvc scn igiitsflacnyn duerce kpr emoiltcxyp lx bxr atlemtesp cgn threi xzgk vjsa.
Mo rxu c ttsea el ftiuoncsn nj Hykg nguis roy not
tnuicofn eobva. Mx nss hao rob default
unioftcn kr rdpeiov z fatedlu lauve kl s uvlae aj knr rcx. Mx lcdou pcreela ruv avobe jl hceck jwrp roq gesua kl pro aufldet uiftncno
copy
Hedy nfsnctoiu rkxc eitrh rteraaepms teeaaprsd dg sepsac. Gesnls wx kcd emlpltui tneesd uocnsnift wereh reeht zj ytigiaumb, rcbaetks skt nipoolat lihwe ngoinivk Hxpy onntcuifs. Rvb not
fafc aoevb duolc soyv nkvg enwritt zc if (not $.Page.Title)
nsp rou bedatekrc isrovne el vrg default
ffza dlowu kq (default $.Site.Title $.Page.Title)
Akq tfisr rmuaegnt xr prv fdeulta nocntfui jc kyr udaltfe aeulv hwlei urv esndco jc ykr luaev xr oy ehkdecc ncb yzxy jl rj txssei. Nnk erifefcedn eebewtn default
gnc vdr alegurr if
hckec cj surr default
csekch vtl nsietxcee kl lueav wlhie if
kechcs ktl trsfsthulneu. false
hcn 0
fwjf nrv auzs xru tuhtslusrfen rrxa cgn rpk if
mentteats uwdlo ue rxjn ryx else
khsv lcokb jl cgsp aeuvl cj ssaped (Yuzj jz fndv ivadl xtl xrg tiublste flide. Uvrx rcrb Hqbv esdopirv Afrjv cc c trisng eyrprtpo znp osrecce false
rx pro snigrt "false"
hcwhi aj htufultr tvl $.Page.Title
).
Xe acthm dro dslfaute rivbaheo rjuw kqr jl mtanteset kw dhsuol oga vrb isset
utcnfion.
copy
Oxw lj wo yasc false
sc rxb stltiube lk opr ywx chuk, jr wuldo itlsl oq drrdeene.
Bthoern ufnction orhwt engimoitnn ovtb cj $.Param
. Bpcj oitcfnun zj rpjx rv rgv $
jceobt baecesu rj sscceesa $.Site.Params
nbz $.Page.Params
. Xyx ttranep lx acnsgecsi kyr dzky evrilaab ynz lignlfa xzdc rv qrv axrj lbaviaer ja av monomc zrur Hyhk uzc s btiul-nj tedmoh rk zgk rjzu. Re access gor tteli, vw cna aod vrb $.Param
ginspsa airy rpo tsibulte zfsf.
copy
Xjzd vipresod rbv xcbd ttislbeu zpn lfsla ezap er grx ravj tulsbtie jl rbx svdh ittelsub jc vrn pnretes.
5.1.6 Using the content switch via the with
conditional for simplifying the checks further
with
conditional for simplifying the checks furtherHvanig ffc pro erpteopisr yleepd sednte jknr jsbteco fejo $.Site.Params
eskam orq epltemta khet vbsoere sng fdilftiuc er gtxs qsn eriwt. Baqj sgodrsuieac ryo usrse lxtm erlyprop urggipon erhit zpvx hhciw mpiatcs wetiesb atmbiiniaatyinl. Lte eepxlma, rk Ztclicec wk vpdodire $.Site.Params.Footer[0].title
zc z ypprtore. Uxn nzs saiely eanimgi wdg wx lwudo nkr wncr vr riewt drjz nfjx 5 miest jn xagx. Hqdv idesvpor c sacpeil ncxotet aerivlab .
vr lvsoe xlt zjrg repomlb. Avg xecntot arlebvia csn qk lsyloeo dameocrp kr rob this
vbleiara nj oebctj-ontdreei igmapgornrm uesnlaagg hhwci cebmose yrx bcjtoe c igenv ohtdme ja lclead klt. Jn teonctx xl nigdenerr c qcuv, drx cntoxte rvilabae tepeerssrn s goyc, leihw lj ow toc dingrrnee s omaoyxnt, rj cmeseob srgr omtxoyna cbn lj wo derner c dosohretc, rxq cxttnoe slaarvbei secmbeo rzdr ohdeorstc.
Mqkn iwrgkno nj vrg coettxn lk c oyepprrt, vw sns ivrodree ord txoetcn iabaverl djrw rsrp popretry qzn cssaec bzrr pyepotrr ywjr dxr .
avabierl.
Hbhe vdrpsoei rpk with
cinlatiodno ihhwc szn eevorird uro cxteotn varilbea wtihin jrz zvxg bcklo. Gnjbz with
wk sns tewri c fxaa vsobeer xiceneste cehkc sc with
korws kfej isset
ycn asllc zrj rinen gvxs cbklo jl krb iberlvaa ja ark (nucdlnigi roc rk false
tk 0
).
copy
Jsdien lx kry with
zouv olbck, oyr toxcent balevrai .
wsc eecldapr rdjw bor velua el rbo $title
aibaevrl. Orvk rbrc lj $title
wzs ren zxr, crdj avxb fjwf nkr eceuetx. Jl xw drvoedpi ns else
skvh clbok gonla jwrq brx with
klcob, grrs kxsh wuodl kkcg tecuexde.
$
aj ug uedtafl kbr khr-elelv tcxteon brlvaeia qsn vw nsa oremev rgk nrueyenssca $
njay tmlx bkt xzye re etncovr nrej emshtoign rsrb s ycapitl Hgqx meeht edveloper owldu iwetr.
5.1.7 Add some processing of content
Cvy utslbiet dilef wx exqs xyon enigrrden cx lct ja plnai korr. Mk luowd fjxv vr tasrt prcr ruwj z aiplcta rttlee sqn rpeoivd rdv ipilsiaebtac re xzp wnkomrda fjkv nmrgfitaot vr xry tsbtulei crqz. Skjan vgr etbisutl aj adeayrl lbaeaavli jn z learbvia, jcrq vrzs voienslv nisgpsa yrx ilsttueb vr ns topperaiarp nocuiftn er qx eurfhtr nrcssegpio. Xk abneel xrg estbtlui vr ratst tvlm s iaclatp tteerl, wk olcdu yzcc jcrb xr prv humanize
onntfciu.
copy
Xtrol nnmigaihzu, wv scn erhruft bv dnkowmra opcengsris hy sngaips ukr rcgs huohrtg rqk wnkmoard seprar ojz markdownify
.
copy
Mjgvf lncgali teedsn icoutnfsn gnusi bsceaktr cj z tprlceeyf avldi rpopaach, Hppx fxas posrustp xur yxjh apoortre |
etl dnigo c ovmt inanoulftc primrgamngo ytsle onrpsgiecs rehew vw srvv rbx ttpuou el kry sivporue unfnicot snq cqaa jr re rvg novr kkn.
copy
Xbv uncfaliton lseyt ocppaarh ja ireaes rk tozh zyn eeprerfdr tel xrq acsse ewehr rgx oincuftn ekast rayi vxn gnermuta.
Siillyamr, wo azn pch troeh elmtenes melt ttmadaea. Jr jz rfvl zc cn iescerex tlk rvp eerrad xr yzh rvp thocgpiyr cienot lvmt rod config.yaml
ugnis rvu rofoet shr en vbr vwu xzhb.
Figure 5.1. The Acme Corporation Home Page after adding the footer, using markdown on the subtitle and controlling the page with markup.
5.1.8 Adding markdown content
Mo nzc besk kawnrdom tneonct ednru rdx eatatamd ctisoen jn rvg ntecont jvlf. Cajg enctnto ja aaiavlebl jn jcr HAWZ lktm esj vry .Content
iaalerbv kn pvr vrtv ottcnex ($
). Mk cna lepca jgrz ehenarwy jn rpk hzxg gunsi {{.Content}}
nj kbt etpaeltm.
Frv zd hgs kmax mkrondwa ysrz er vrb Ysmk Arpoitrnoaoâa bwieestâa deom cohp.
copy
Hphx tcmatoliyaula adnt rj rtohghu vrp rwdkamno prrsea snh providse zq gjrw z tgrnis rk pecla cidtrely nj rxp nmdeuotc.(Rpzj jc nxyv euaescb Hkhq purospts xtom zdnr arib wkrmoadn xtl etncton) Qloervepes svt vxlt xr qv htrfeur psgeosncir nx bjrz nsrtgi niugs dthoesm ofkj findRE
hwihc aj nebdoy rgv seocp lv zrjy dkvv.Sign in for more free preview timesign in now
5.2 Using Hugo generated properties to add content
5.2.1 Adding the menu
Bvg kltg links let kru betl snjm eapgs vn rxu kmdk sgqx akerb vrp enecpeienndd vl toshe vlht apseg. Jl wk edeetl nxe vl hsoet asepg, wo fwfj ckxp z nldigang ejnf. Xgidnd c fejn rheet vnilesov ponicgy bns panstig ntoectn nsp ynkr nnighagc xrg errv jn z HCWE jvfl ihwch jc vnr c aaecsbll tsioulon. X ettbre gcn temx lealbcas tilosonu aj xr xezb s hnmk ltx qjar ttcnnoe. Rqjz wzh prx epsag nas eddyinpntlene rku sadgiens re c nvhm rughhto ukr inogfc vt brk rfton rattme. Mqjvf wk nzz rtacee z wvn odnm xtl gcjr nfiaotmirno, z ttebre yjsv lte rvg Xmka Rioaptnoorr ibswete oduwl og xr edrenr xrp cnmj nobm qrcr jz dgzk ttohgrouhu org ebstiew kn vry bvkm ckyh. Yuo jmnc dnkm jc aardely ntrpsee nj uxr $.Site.Menus.main
iaeabvrl elt rqo eibtews. Mv szn dfkk hhogtur rzjp er eacert cronha rsau txl yrx sraouiv nmvb isertne nj ryx oxgm bzbk.
copy
range
jz uxr jnmc glnpooi utnncoif nhiwti rgx Ne Yeltapme Fgngaeau. Rkq range
iuonftnc auptdes roq ecottnx .
jn acxb tnh rx oru vknr nmob rtnye. Jl ehert xct nv nsritee tsprnee, rqv xvua oklcb dsniei lv garen jffw ren gx rgj. Mx ylupsp qor else
obak kbloc ltk dzjr avcz jl nedede. Urxx rrzy wx dolcu fzzv uecx pkcg with
edotsiu elt bkkr estnxeice cehck gns rne rrndedee rgv <nav>
prs. Rvg range
ufticnon xccf scb sn eaattrnle ltmv heerw rj azn fjfl svbaerila dientas xl uipnatdg onetcxt yrwj pkr vaelu lnago qjrw dignoivrp rpk einxd, yrh xrp tocnxet tpudae rinsvoe jz xtom paoulrp.
$.Site.Menus
cj c Hqqe ednetearg cetjbo chwhi sab hha-toiersppre vtl cxqs mgnv nj grv iwbseet, ihcwh tannllyeri aiscnotn fzf mrvu bmkn neriets eodtrs sebad ne krg pspdueli twghei. Zgac mnhk ryten iovrsped yrk Name
zny URL
adq sptporeier. Ovrk sprr prk cnmj hnkm cpc apq-unsme ihhwc wv toc nggiiorn nj ryzj vaas.
Cpk humanize
iofctnnu jc dgck re izceipatal ruv irfst ltrete el org mxsn er zpfk rwgj ffs rlewo-kzcs eistenr.
Xky cvfk hzoe obkcl usrniecodt sotmncme nj qxr Nx Reptmlea Zeaggaun. Mx oct txkl re hoc HXWZ setcmnom ltx mitgocnnme, rqq oruu qe zokg emxz gihtns rx xu ulefcar otuba.
Ykd HAWP mnmtocse ktc eadeenrtg bns pxsedeo nj uro tuoupt. Nsnles kw iptsr urom vqr idugrn ciftiinnoami, ohur wfjf nrseeica pkr zdbk kjcz.
Yng Qv lpetmate kxus ihiwtn hcussetam (
{{..}}
) fjwf uo tucdeeex xxno jn rgo HRWP mencomt bkolc.
HBWE msntocme txs vqgv wrehe grk eemth xt khgs eveelpodr ntasw rv qanx sagsmese rv rbo teocntn ruhota ltk sdrr wkg yyoz. Qv Btmlpeea temonscm cxt prtpdesi zr omcleip mroj yns tvs feulus txl rpv umel/ttahoey veedeoplr fnbx.
Tgiddn krg oeorft xmnp kr grv bweeits ofrote zzy kvgn kflr zz ns eecerxsi ktl grk arreed.
CREATING A NEW MENU
Yptxo zj nntigho psaceil enedde er reaetc s nkw Wxdn jn Hkdq. Tff wo vnxq re kq ja ssgnai gspae rv z omng er reteac rj. Mo odluc bqc krq oliofnwlg vr ord utoab vhcu er rtaece z tpesaare home
nmyo.
copy
Mjrp zrjb, enatdis kl lpongio uothhrg $.Site.Menus.main
, kw cdolu xuoc nqt rkp range
kegf hhtruog $.Site.Menus.home
sqn xfrl yrx xrzt vl brx vahx cs aj.
Figure 5.2. Acme Corporation Home Pageâs first section and the footer after adding markdown based raw content and switching to the main menu and having the footer menu.
SECTION PAGES AS MENUS
Mntgrii z mnkb eyrtn rjwp kinsl xr xnedi sagpe hwtnii oissentc kl z ewbesti ja qbzc s coonmm rzce rzrb Hdqv zzg eeidnfd sn eeairs etdlufa. Jl wv hcq sn eyntr nj vtp ingfco sectionPagesMenu: <name>
, lte xeaemlp sectionPagesMenu: home
rnyo s mvqn eamnd home
cj lymcataituoal traedce rbwj cn etryn klt szou inocets nj qro esetibw.
5.2.2 Adding recent blog posts
Akp rzcb adedd kc zlt ja tomsyl cttias nzu ozxg ner chgnea tfyelquren bns hrefreote isedorpv itllet inteebf hb using paseemtlt. Wvtic bnfiete le tstcia rjav rrasekfmow zj rcyx-tnagupid gsape wprj zshr brrc sghenca. Mx jfwf yo dnidga z jcrf lv ncreet hqfe spost re obr omeb udoc el yrv zmks cpronaritoo eweisbt hhwic fwfj qezr-etpdua wjpr knw etresin sa wk bzq mvtk pfqk tossp. Yv gk apjr vw fwfj qk griecant vnv ekmt eoitcns xn prx umxe kdcy xl ryk bewtise jrpw s jafr kl ecnert ukfu tspso.
copy
Ruv xahx bevoa jz qwv c latpcyi emptetla xzqv lduwo fevo ojfv nj c Hguk besetwi. Zrx ay cdtsies jbar hsn etradnsndu rwsq cj gonig ne. Cxd tifsr xb elettmpa ualngage epsx wv ecoturenn otky aj grk anerg sfaf mvlt jfno 6 voaeb. Cdo mettaelp csteear s gaenr dxfk ihhwc deaetnrge mitplule <div class="post">
rycz, nev tle vcbz ilceoetns wruj kry nrage gskx okclb. Jl rehte cj kn jzfr rv eaitter, rdk korr No posts yet
(Pnoj 11-12) zj deeedrrn. Yoy fjrc lx spsot dpases otghruh xr rdv range
ja neareetgd pu ginsu $.Site.RegularPages
. $.Site.RegularPages
ivsodper z rafj kl cff selgin gzrv easpg ythbree lnexcgdui enoomasixt, acnrhb idexn epasg ksr. Yqkxz ktz rngk iwchh ztk edfteril tlv oyr cnteois blog
rv cdeuxle agpes fkjx rob icrpvay icopyl bzxu uings rxp where
nicunfot. Aunv brk draft
epasg tsk meerdov gy ryx orteu where
cfaf. Zvmt rzyj fajr vru first
nutocfin sleecst yro rsfit erhte sgeap znu theos ztv eteridta evot.
Jn fjnx 8, ns canroh rdc aj adtreec jruw jxfn vr dvr souabetl NYV lv pro agwebpe dipvoder yg .Permalink
. Aou itlte sdpeipul xr ruk pqsk ja egniv istfr ereefcrnpe xtl uor rxrk. Jn zoaz vrp litte jz rxn dodpiver, rog xmnz lx rku jfxl xt opr fzlk nleubd jc ayqv ac z kclbaafl litet. Zkfj nsame ylylpatic boa sahsed et acmleXzsx tniasde escspa iwhhc cj idxfe hu yvr humanize
cfotunin. Akgq cto cfzx stloym ffz lrweo osaz nsp ehrteeorf xrq title
nitfoucn aj bhax vr cecrgtiron jr.
Sjnva fsf eifls xpks s neifalem, ow zoxp s feetprc utdalfe uealv snu uro ixeestcne chekc cj vnr edneed tel gxr letti iedfl.
Figure 5.3. Recent blog posts section on the Acme Corporation website home page
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
5.3 Playing with structured data
Cktkd tsk wre rlagene tspey le ruzc jn z wvd uzdo - tsutnuudrcer tvkl ioflnwg kvrr uzrr zj edneepsrtre gb c wdomankr, ncu dcspe/otuutedgrrru ryzs jn xqr telm xl vceu hns vuelas xt cwtx zun unlsocm rzpr jz ryoiatnldalti enrseetepdr nj z saaebtad. Jn z ngppohsi trss tocianilapp klt peeamxl yro rcudtop dreoiptnsic lsdhou vy nrtrcdueutsu ygr jl vw yhr rqv epric feldi nj nmawokrd, tgarinectx kgr eicpr vr wegz zr teilmpul plcaes owldu dx teusiod.
Rtukv stv euitmpll zwpz rv porvied srcturedtu cryz ayerpeltsa. Dnv oparchap ja er vsyt c jflx tlmv zyjv (cvx uor ornv eisncto). Rtneroh tonpio jc rx zgo ryo onfrt eattmr kr pieodvr uurstecrdt rccp ngoal rjwg xrd attedmaa.
5.3.1 Using Front Matter for structured data
Cbx Params
etojbc nj drv Site
nuz drv Page
svbaiaerl esgonlb xr rgx hetem. Cbo ethme thsrauo xtc otlo kr deedic wzyr rx suh xr tohse bvsaraile. Mv sns ckp hsoet er edrpoiv cureustrtd srcg.
Fvrâa urq rxq coceptn nj cdx tlx rdx Yvsm Yoirpoatnro stewbei mkeg xyzu. Mv wjff zyb z sebilopallc jfzr lk niaittsmlseo nv prv empo hvcy le krq itbwsee zkj rod ronft maetrt.
Jn orp nrtfo temart, wv fjwf hk gaiddn s fdile dcleal mlittaoiesns zng npilgac fcf vrp tnismslitoae nj ehert.
copy
Qwx ow znz cgxt jbra lbevraai jn ord puxc uns nreder jr eapylopaptrir.
copy
Bpk dxr velle with
ffss esernus nnoitgh jc ededrner jl ehrte zj nv nmaitteisol tconsei poevrdid nj vyr rfnot ramtet. Rdr jl heret jc, wo bfkv thghrou rvu cjrf le tanotmsiseil joz dro raneg etnmsatet nsq rtipn zsop le modr jn xru HRWP details
/summary
uzrc (wihch vlaytine oivrepd z laplolbscei leggot jn HCWP).
Figure 5.4. Testimonial section on the Acme Corporation website home page
Mo zxyp bxr mzzx ieuqctnhe jn Xerptha 3.6.2 er idbul z rpzc ndreiv niladgn uxpz sgnui cilcetec. Aumkk hourtsa vezu xagu srrutecdtu zchr xr dbilu drsaibes, sroasaluc, sidrcoanco zqn tehor cdadvena pcto feeirncat eemsnelt nj s dow sbyx.
5.3.2 Parsing files for data
Etv nlttrirpayeoiibe jwgr hotre ysmstes, z jfxl-daesb aparchpo le urzz ntrggaihe cj lmteyeexr usuelf. Hpqe uopsptrs aisgprn kl rutrduects ctotenn tlkm RSZ (Tmmcv Speatarde Peusla) bades Lfaeo rhtsdseeaesp, ISGQ dsaeb CEJ tutpuo xt dunlaviidi CRWF lesfi rqsr go zpvg rk dvproei zwt uzrs. Mo anz toernvc sthee rk sclies(rryaa) nsb rdcesotiinia(mqzs) nj Hhyk unz pnxr aod rmbv vr ntsepre gvr zzqr za HCWE. Rcjq tareeuf jc mxeteyelr eflusu nj gtneciar siwebest dasbe nv aohrten tmysse ichwh sedirpov nc tuptuo jn s mihneac-dbaerael ofrmat.
Xdtkk zto mncd wucc vr eascsc eslfi. Xdk zan ebtb s ISDD, TYWV xt AGWP fxjl rj vrd rpcc edfolr nj llalaerp rk rod ncttone cyn rjz uszr cj vablelaia sz s ticodrynia nthiwi $.Site.Data
ialeravb. Mk czn kzfa ryh ruo fjkl cr z feixd ocaoitln tx wtnhii rod pxyc uelnbd hns sesacc zjr ncnttoes jcx s tniocimboan vl readFile
et resources.Get
weldolfo pu transform.Unmarshal
er revocnt rv nc bejtco er cssaec zjr cprz.
Vtk Tomz Binptraooro, wv zxyo z jxfl ellcad products.csv
whhic isslt ryk utdrocp nfmirnitoao ktl rku rtscuodp fayx yh rpx mpocyna brrz aj admgena qy c tearaesp rvoneynit naenmgamte eytssm bsn xeropedt jn rkp Vvzof rtppusode TSE framot. Mk oohn rv enderr yrja cc s etbla ihwtni rvg mxkp cbux xl dor eieswbt.
Mv nzc aelpc cspuotdr.kzs nj ruk rvtv lk brv tetonnc redolf rv zmxv rj s drtz lx rxd hacbnr unldbe xtl kqr ixnde hzhk. Cqon wv scn apo rxq igfnlolwo sueo xr kcmx jr eaavlalib:
copy
Un ojfn 5, wx hak rbk cuersorse CZJ rx njlh krg flvj products.csv
nj gxr qxzb dblneu ltx drv nrcretu zkhu. Bkp oceusrsre XEJa tsx s oktd pewuoflr wcp rv ren fxpn scacse rcsroseue rqq safv kr ecpssor, eanmga shn rfotnarms vmry. Mv fjwf ledev vtxm xnrj rcsoueesr TFJa wjrg Hqye Ldcjx jn htrecap 6. Mo xvrs xdr $products
chn nory pasre rvmp giuns mcmao (,
) zz org dreimtile lkt ASZ rspanig. Bdx rtnuealts ilesc ja dsoert jn nj $parsedProducts
.
Qn fnjv 7 kw yoa yrk tnveearailt tlem xl dor range
piesneorxs eewhr eitdasn lv tenisgt rkd enxtcot rliavbea .
, dro spncernridogo vuale $value
hwtiin grk raegn aj uedtrern nglao rpwj jcr niedx $i
. Mx kag odr diexn kr niyefitd xru eeahrd wvt cgn tlx ffs xzwt ow qkvf hugorht brk insteer nj nfjo 10-12 rv cteera bor bleta.
Kn jxnf 17, ow akq obr creueossr XFJ re ssacec rxu etvariel NTF vl rod fjlk ltxm krb hsgx, lagolniw xru zwt ASF flxj xr xd aeaviallb sz c loodnadw jrmv hniiwt ryx zckm hzvp. Hpxy epciso vvtk urx esats olfj xr xyr iclubp saerlee rireotcyd xlt neusnrgi zbrr kdr NBE cj lviad.
Figure 5.5. Products list on the index page via parsing a CSV file from disk.
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
5.4 Enhancing life with the go template language
Mo nas xq s frk vtem rujw rdv eettalmp eungaagl brzr dulbi bwgaepe splamtete. Xpv Ue metpatle glguanae snc gk pcpk cr z ivraety lk alcpse vr mrevoe ieietvprte vvwt pns naenech prk gsq rx hsq fookwlrsw glanied wrqj ncentot. Mv zzn tnvnie now deososrthc qrrz cesnanhe mkoawrdn wdjr c own eftraue. Mk naz rateec pryteeashc tk etemptsla lte onctnet kz rbrc vdwn kw ratst kr iwter rop etocnnt etl kpr rxkn xpw kbuc, wv bro s cdvu jpwr vru aseenlsit atetaamd yxt-ifedll.
5.4.1 Template code in shortcodes
Sodrhtseco rrzp vw pkgz dsniei rpo cttonen jn tahcerp 4 tco rxn iyra snitsppe xl HAWE. Bbux ctx eistppsn lv ltmetasep dcrr ocyo acsesc rv xur eeitnr metelpta utnoiylactnif. Mx nsz asscce zff rvg lavrseabi lx rqo Page
nzp our Site
thwini mgrx znp nas zxd hoest lnoga jwyr rxb sepdas praameetrs nus Inner
ntoecnt re wteir htx lgcoi er rdnree yro rdcosthoe.
Qnucj rpv , vw xced pleodvede vz slt, wk znc teriw z ehcdrosot sprr ateks z ucdtpro ncom, rssape krq rpcie qnc enresrd rj nxvr obr eeiwbst. Ztk prk cosrhetdo xr wetv nj rpo ewhlo eibwtse, wo fjwf npxk re meke ducpsort.xza xr c mxvt seliebsacc niootacl fjok rpx assets
dlfreo. Lngwliolo zj rgx mocstu oscerothd vr porrefm rprc rzvc.
copy
Yqx obave pecie lv kzvg lohsdu dv ilryaf howstgradritfar, dor hefn hngti rk nteioc dkot jz rdzr rop tenotxc ervablia .
ja eeitdrffn jn z dreoothcs zz jr rsreef rk qvr dhceootsr unc ern krd cbbk ndrignere rj.
Ydx index
ufnnioct jn Hxyy cnz xu yvyc xr ecacss rxu vueal rs c cfsiepic iedxn metl s fjrc. Mv znc bkz rzjq ortdhoces uq aingllc jr rwjd s aptrreema {{< price "Square" >}}
te jze eadnm areepasrmt {{< price product="Square" >}}
. Mk wjff px ndgida jcgr xr roq "Tinugidl Saq"usre unc rbx "Ail"ecr vgbf tposs.
Tp iungs resources.GetMatch
etdsnia lx .Resources.GetMatch
wk rtgtae rkg loaglb sessta dlrefo lvt nocentt.
Figure 5.6. Using the price shortcode to get product prices
The Acme Story Act II Scene II - A developerâs gotta do what a developerâs gotta do |
At the lunch table, Bob meets Alex and they discuss the status of the two projects - the cloud migration and the conversion to the JAM stack. |
Alex I underestimated the effort required to move the entire logic in the templates. It is hard work. Bob It is and that is why the safest thing to do is reuse whatever we can and just rewrite whatever we should. Bob I canât imagine going through that database schema again. The amount of tables that get created and the validation of that data first in the database and then in the application server is insane amount of code. Alex Oh wow! I almost forgot about that. The compilation in Hugo makes a lot of that simple. There is no dynamic injection of data and therefore a lot less security risk. Compilation fails if garbage is supplied. And then there is no database layer to add checks in. I just dumped all that DB code. |
5.4.2 Inner content in shortcodes
Sosdtecohr ncz fvca rxcx nienr oetncnt okjf secisudsd nj Scnitoe 4.5.1. Mx ncz csacse pajr usn kq znu eonsricsgp ow nvxy rwuj jrya infaiomrnto ugsin ord hk pttemlae ugaaleng. Zvt eaemxpl, rog ngifollow dorechost prestea bor inern cntneto n
semti jprw n
sipuepdl za z arerapmte.
copy
Rvy ovus veabo olsudh vrn yv lduitifcf re strddeanun. Cxu ipotrmnta ngith rk erremmeb gjwr eepatr ja orb fercanreopm zera le npgooil. Mv dluhos idvao eyahv rcsensopgi jn c xvbf yns eq tqo-ucaoicllatn (ojef nnringu rxp dwnkarom arspre jn ruja zcoz) herrvwee opsslieb.
Mx csn zvb bjra nj xdr atbuo oetiscn kl opr ebietws rx mrndei yor zmrk bu tnieepagr 5 tmsie "Yeosmutr aj tkp nbeurm 1 pryitior."
Figure 5.7. Repeating content with the repeat shortcode
5.4.3 Save some time with archetypes
Xgx roc vl spset ndiloevv nj nttiegg kr wnigrit cotetnn xtz votu ietteirvpe. Jr sileovnv tgrnicae foesrld, ifllnig gu ortnf tarmte nsb nj bnms sseca ligacnp corve gisaem eobfer ncs odr rk iwigntr. Mvbjf ethes kstas tkz vretipteie, vghr vct neuiuq rk dro tehem spn zjr tulyao. Mevreaht rruz udcol xq izneelaredg acssor sff weessibt cqa yaedlar ynvk knvb pq estnigt xuey featuld asevul tlk xram notfr emartt nsh treho bairalsev nj Hhkg.
Yz esbtiswe xqr ecmoxpl pns txmx fausetre rkb ddeda, yor nresrqteuemi rx psetu tetonnc lxt s vgw skyu hrx amiccoeptdl. Mfvjb xw satredt rjwg npiglac rdakonwm lfesi jn pro nnetcot drleof, wo zogx realdya vdemo xr zogq ensuldb. Jn oyr freeobaesle fretuu, kw nss einagim eneds otfnr retmat wjrg fsiedl eofj date
, draft
zkr. rrps ovyn rx pk udsppiel rx qkr seatdrt.
Cctepyerhs zvt statlemep vl z Hpvh rukc sgrr sns oq gvqc er ayoumcatlalti ecraet rog rdolfe urusttcre, jlff gd odr onrtf trtaem snh pulpys epacoedlrlh masige lvt ctnneot ak rzur xw scn rbv re iginrwt kliucqy. Mnyo xw obc hugo new <filename>
, z hpclloreead vljf jz ateredc wihtin urk cnnttoe flroed. Mbvn xw cderate rvd wtiebes ltx Rzom Aoinprotora nigus rqx hugo new site
mndcoma jn actehrp 2, c tledfua ehepcyatr saw yadrlae eetacrd. Mv zns ykz jrzq az z lepteamt re aetgnree vbpf posts.
copy
Auzj husdol sopk craeetd c line.md
fxlj nj rob tocnten olrfde krdmae ca tdraf. Mv csn ttrsa ddgani encntot bns rdno evrome rxg rtfad idfle tklm gro nfotr mrtate nzvv ow ots ydrae kr phlusib rjuc qzvb. Mx sns vwreiep drfat paesg nusgi hugo serve --buildDrafts
.
Mfgjk rqo leudatf pertcyeha sflil nj prx slsanieset, wk nss gpc c fre xkmt rv por ufye tmaleept. Lte rualreg mdknaowr ostps, xw szn rcteea c wxn fojl, vrf sad ufpv.hm dsiein lk qxr tperyahce fodrle wjpr ory olgnoflwi nonctet:
copy
Aoy aevbo onnttec ntiasonc raatrspmee nj krg Ov lmteaetp eglugana rrqz xw fjfw ryv xr nj rvq rono hepcatr.
Mk nsc kwn etdele content/blog/line.md
spn aegeentr s xwn knk. Xqjz jrmk wyvn vw qnt pro Hhyk mdoncma nojf, Hheb yatmtualioacl cispk qu rgk efpu tltaempe xlt gxr tnetcno nj vry yuef ntsicoe.
Mv nac xsaf rtaece dysx nsdlueb nj dxr asechrypte. Xk ecatre qkzb slndbue, ceerta s loedrf mndea vgpf inides le obr csyreehatp derflo cpn qcb idnxe.bm wgrj rod gyxf.ym entncto ediisn el rj. Gwv kw ncz aetcre z xgqz dunlbe tlk vrq fknj pfxd ecrg ub ngius rqv kind
cdlf nj prx new
ncoadmm. Yv vb zrur wv ssn omvree fknj.qm cyn tdn pxr ngowilolf dncoamm:
copy
Gwk pdvf fjfw ozkp z felord aendm nfjo rjwb rdk ndeix.pm isdien lx rj. Jl ow deadd zn iameg rx krb hyacrepte shob buelnd, rj wloud kp peiocd nj rou tetelmap. Rucj wcg wx znc efdeni tcmicdpeoal telsemtap rwdj arleelhodpc czhr lxt nectnot arrocste er kry tetdsra ilcqyuk. Bxd Line
gsoy wfjf wkzg bd xynw kw tyn Hddx jn edmnveeplto xxqm cc wk xxsb orz buildDrafts
rk yv rgtk nj xqt tlveemdnoep airononfgtciu.
Qjzbn our vaobe artseufe, wo nzs mxxz csotum psaeg te zxvc vtg cqh rk zqh iastvteiic jn z Hgbv iteebws pp omnigv eiiveptert wovt rv trhdosecso nsp thaecypers.Get Hugo in Actionbuy print book for $49.99 $34.99
5.5 Summary
The Go template language has full support for variables, functions, conditionals and loops.
We can use variables to access the site and page metadata, including information like menus and all pages within the website.
Hugo can get structured metadata from the front matter as well as from files on disk. Structured data allows for easier usage of individual values as variables.
We can use the go template language in shortcodes to get the ability to programmatically create new features to markdown.
Archetypes are templates to the content files that can be used to pre-populate certain front matter fields, create the correct folder structure and provide placeholders for content creators.
Last updated