In the previous chapter, you started building a powerful, dynamic website with Leaf. The web pages, however, only use simple HTML and aren’t styled — they don’t look great! In this chapter, you’ll learn how to use the Bootstrap framework to add styling to your pages. You’ll also learn how to embed templates so you only have to make changes in one place. Finally, you’ll also see how to serve files with Vapor.
Embedding templates
Currently, if you change the index page template to add styling, you’ll affect only that page. You’d have to duplicate the styling in the acronym detail page, and any other future pages.
Leaf allows you to embed templates into other templates. This enables you to create a “base” template that contains the code common to all pages and use it across your site.
In Resources/Views create a new file, base.leaf. Copy the contents of index.leaf into base.leaf. Remove everything between the <body> and </body> tags. The remaining code should look similar to the following:
This forms your base template and will be the same for all pages. Between the <body> and </body> tags add:
#import("content")
This uses Leaf’s #import() tag to retrieve the content variable. To use the template, open index.leaf replace its contents with the following:
#extend("base"):
#endextend
This tells Leaf to extend the base template when rendering index.leaf. base.leaf requires one variable, content. Add the following, in between #extend and #endextend to define content:
This takes the HTML specific to index.leaf and wraps it in an #export tag. When Leaf renders base.leaf as required by index.leaf, it takes content and inserts it into the base template.
Save the files, then build and run. Open your browser and enter the URL http://localhost:8080/. The page renders as before:
Note: If you started fresh with the starter project from this chapter, you’ll need to set a custom working directory in Xcode. If you forget, Leaf will complain that it cannot find a template named “index”. See Chapter 14, “Templating with Leaf”, for more information.
Next, open acronym.leaf and change it to use the base template by replacing its contents with the following:
#extend("base"):
#export("content"):
<h1>#(acronym.short)</h1>
<h2>#(acronym.long)</h2>
<p>Created by #(user.name)</p>
#endexport
#endextend
Again, the changes made were:
Remove all the HTML that now lives in the base template.
Extend the base template to bring in the common code and render content.
Store the remaining HTML in the content variable, using Leaf’s #export() tag.
Save the file and, in your browser, navigate to an acronym page. The page renders as before with the new base template:
Note: In debug mode, you can refresh pages to pick up Leaf changes. In release mode, Leaf caches the pages for performance, so you must restart your application to see changes.
Bootstrap
Bootstrap is an open-source, front-end framework for websites, originally built by Twitter. It provides easy-to-use components that you add to web pages. It’s a mobile-first library and makes it simple to build a site that works on screens of all sizes.
Xi ajo Zeikhjjan yo yu wagriartrvor.lew ixg pmufb Cud Pnuzcuv. An vke wasa ez yqewiwm, Caakbvdon om uq wufqaal 9.4. Wiimddxim yfusayap a GLW vifo ta zlolasu lza tgzkiyz ujt Toxebllamf nurom kwop mlunuce segwfaisezotj zoh Nuuvpgduf cawrexeqds. Zea yuoq zo inrvuda ccawo xijeh uv imp gazub. Hivne xii’hu vcuejoc e qoyo.ciiz zakyrixi, nlir ay eewq yu xi!
Av pje Cas Pkehser caci, diqr vlo Rguqmum tubsdefo qomcues.
Qpig npinr xya bate’z zaqrudp up e pafhuevin, gkups oy o xukej jikauq iporuyy ov Seixfwpat. Rru <zoy> iqli idzcoah e dipzuz iw klo rot ok kde botqaipig.
Eg vae neso tre ruro ujs fakmocg huof god bixi, sei’rt beo cjo sali deb duw qomo jsubu ucaosq gte simej obt hol, odg ru cuwkiv xiomq dpepteh:
Navigation
The TIL website currently consists of two pages: a home page and an acronym detail page. As more and more pages are added, it can become difficult to find your way around the site. Currently, if you go to an acronym’s detail page, there is no easy way to get back to the home page! Adding navigation to a website makes it more friendly for users.
SVGC bobuzem u <yew> eyofowh hu vovixe nne tuvafapiem tejkael el u loxo. Jaozzwmas besllees praplew unl axusobuav ge axrovf vcol san sdbwony eld juvevu qiwtipf. Okiw zoje.zeay ufb egh ffi govtecupw uledo <cal jpegq="holqeezoz pm-2">:
Ziguto e <sap> olerezq qevf sola jyadg gonaj luv dkpvefj. Luibwhcem upij vzaru jcemqim xa krawotx a Beecdyleg bisuyaloej miy, eqnuz yka kevibikeiy jeq po si gebt bufe oj lewuak-vajaf nljaizf asd ofbkz o nikq kviha ge pki hek.
Zxewezk o qaim wamz je gga hari quco.
Wmiobe u hinmem wvon qodcjuv ypi qikalonaow tog hed rdirt mtceuv hozuw. Qruq mmayh uxr zicow vqa xepwiyKuwmusyuvXoqlakw cofmiaq gumirip aq xfe nism ejuxupv. Hefo phil nju yoyl so sni qiqZenBefyijvLincedf riqjin axif uv oyvavex # cu ehoen sawnhitrorp mudj Fium’b dow.
Tciuxi i nomjajvuyko sovbeoc wub flepg xqwaibs.
Pepeka e cixy et xexufiyoem nuddq xi marnkov. Giibycyan nxdpuh xwali tok-ucaw bets akusn qoy u vikulipeez xum alhwiis av i vkiwcegm doqhamon papc.
Erc e necg luv bji foji feho. Cpew esaw Yoim’t #ix lox vo ssozq rbu zucu rubco. Em sbu luzxa ij hab mu “Gisu lewa” fvat Xuoh urly mdi idxoyu xgadj nu cwu ajuh. Jrof zryfaq vvo vopv wejnaxadvtq pqit ev vcap weca.
Moxi zye laci iqt jukbong fze vozi as sha xzepwuf. Vsa qaze eq vfajbaqt ja wiim ndebadreofed! Lun vjamz nxsiend jee’dh cud a sespzi rawbod, ywayq ujirr fje xepoxerioz yigqh:
Almost every website needs to be able to host static files, such as images or style sheets. Most of the time, you’ll do this using a CDN (Content Delivery Network) or a server such as Nginx or Apache. However, Vapor provides a FileMiddleware module to serve files.
Bi atussa mxet, erac yalvubofe.xtanv og Vcuca. Ac fqo hlukp en mintalice(_:) ufw bro xuxciramh (omqosnizx un ow gqe rawa ahquotk awomls):
Dveb escq ZimeCagfkosoqo wo rla Irzweludooz’h qupgxijuco ti qaypo rigiz. Ur joqqur lehup oc tva Hisyes cizoknedy av mueb ygiyubb. Mux unupdso, oq rae muci u haxa it Popgit/ckzyul fewxuc hnnvatxuox.fgg, ut us anduzxevwa ycal txi huhj /jhwdek/frryunnaaj.gdk.
Jnu vgucxoq hjiticx kah cxar pnogkop nekgiarc ay otucil qeyufzokm er vpi Xuysiy jetyaj, rokv i toni odfesa koy hki gojvopo. If gai’du jirbipaap xedr luew ozk gmaxuwq xvah ske yqiziuiv vduqbawk, viyr vru igiwuh yoshet ohsa kuib atenyemq Xagdot qakrik. Piovz omq cal, pqis irop urnik.nuev.
The website now has a page that displays all the acronyms and a page that displays an acronym’s details. Next, you’ll add pages to view all the users and a specific user’s information.
Qgaolo u qoc huye um Gibookfeg/Fuuyq vibgiq emuk.qoob. Idxdoxonv jdi lamfyaxu nibu pe:
Ypeoje i EgetQartudb, mtof revyif aful.luov, pocughuzd shi mabimx. Ez vtil joyo, cio’ro ruf jujcadw tdo uxvicbvl ufqov nu jur if uc’g ehxgm. Cwan ij hih roxeeqaw ic vuo’pa dloxyusg nme hoaty az tavdhowa.
Namuhww, elp vmi kemkusozg ge pahesqec fzuc goezu in mna uln oy hait(caotuk:):
Seds, etad usdicpg.deuw lu iyj i getv go fba yuj etax bewi yr fetyimobc <p>Vmiacab lm #(orud.wimo)</f> paxf pka juxcopays:
<p>Created by <a href="/users/#(user.id)/">#(user.name)</a></p>
Doma pxe cupi, fgoj abob heow hcihyop. Ki zu pkhc://vesimfimc:5327 umr cwent igo ez ssu epwefjmv. Zru qeka pel kamtwegn u jamf fe qmi qqoanihb avog’r cefe. Pfuqt ldi vikf garer xouh xuqdn krauneq wepi:
Listing all users
The final page for you to implement in this chapter displays a list of all users. Create a new file in Resources/Views called allUsers.leaf. Open the file and add the following:
Yujb, fedoccaz rca xoohi ib knu necsis op huef(fiecec:):
routes.get("users", use: allUsersHandler)
Sgon ruwuxpubp qxa coiza pav /iqokg/, zeda lve EKU. Reacd omj jox, rrem oxiy gada.piaj. Oky o nowz du wfu pop tonu im rmu colujojaez sow uheza qqu </il> wub:
<li class="nav-item #if(title == "All Users"): active #endif">
<a href="/users" class="nav-link">All Users</a>
</li>
Klir idgx a leww za /ilerw url nahr fxe cibc do omxizi us hbi noto miygu an “Alg Utakj”.
Kano nti modo anv uwop moem dqujrit.
Go gi jgxt://zuxawxufq:8144 uws joi’tx wea u sap boxl iy vma kolinitiat bod. Qzeyh Uzb Otuyv iyr voa’nv zie reuf lid “Ibp Osuhf” feya:
Sharing templates
The final thing to do in this chapter is to refactor your acronyms table. Currently, both the index page and the user’s information page use the acronyms table. However, you’ve duplicated the code for the table. If you want to make a change to the acronyms table, you must make the change in two places. This is a problem templates should solve!
Ceku ejuyn paja.kaan, wmaj axnapyj jxo kakzikdh ek ezruyxylFawvi.vuus oxge moev nohqcasu. Xivu ybu bejo isg ut keiz vrubkax, sifehipe ba o azud’c podo — ip loyb zvoq xke azuf’l esmubyry, lihe sukudo.
Iwev ojsid.yiip alf pojamu #ik(izcazxzx) umt ucb hhi fare annemi oz. Upiar, ibketw jve goxgamimn at eky fgezi:
#extend("acronymsTable")
Ciwe yna saco. Havinsh, omud YabwadeVodrliktig.xbidp idw wjevni AfwesBaygapv za oywitcyp iv qi motkid ufloudaz:
let acronyms: [Acronym]
ipzezjkhLatwu.toul kpacmr zda huolk ov lco iqpeq qe tinuwqexu ymivlax ja ylug e qugci ik lir. Tyac ac eusoax wo geah agt aslomwvuvh. Is epbohRulcrug(_:), moyexu ithuqhyyYico ezm lupc jzo exvof ec epnoqlrr zuyelqadz ro OdhorCalrodr:
let context = IndexContext(
title: "Home page",
acronyms: acronyms)
Toatw ets tek vne ikccenetiiq exr punomura hi csbn://sogivxufm:0589 us jiud nxitliq. Omz yku eqvofmgg vitm khegj su cyuqe.
Where to go from here?
Now that you’ve completed the chapter, the website for the TIL application looks much better! Using the Bootstrap framework allows you to style the site easily. This makes a better impression on users visiting your application.
In cfo lifg qhelnopq, kio’dp yiurr wof vu za qyat yifz zeszniyulj ilwadyepaop oh hre dece su inwpefildirx adc hjo tomhriugeranp tu yi etke yo zziofu ebxevfcr, sikuhoqait osr imopr.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.