<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by ramkrishna on Medium]]></title>
        <description><![CDATA[Stories by ramkrishna on Medium]]></description>
        <link>https://medium.com/@ram2386?source=rss-783d661f67be------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*I17lCqfzthnyA8zv0TjzCA@2x.jpeg</url>
            <title>Stories by ramkrishna on Medium</title>
            <link>https://medium.com/@ram2386?source=rss-783d661f67be------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:53:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ram2386/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introduction to Leaf for iOS]]></title>
            <link>https://medium.com/globant/introduction-to-the-leaf-in-ios-applications-64ceb8fa3f54?source=rss-783d661f67be------2</link>
            <guid isPermaLink="false">https://medium.com/p/64ceb8fa3f54</guid>
            <category><![CDATA[leaves]]></category>
            <category><![CDATA[vapor]]></category>
            <category><![CDATA[templatedesign]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[serverside-programming]]></category>
            <dc:creator><![CDATA[ramkrishna]]></dc:creator>
            <pubDate>Mon, 11 Jul 2022 11:45:51 GMT</pubDate>
            <atom:updated>2022-08-25T11:04:19.054Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is leaf?</h3><p>Leaf is a powerful templating language with Swift-inspired syntax. You can use it to generate dynamic HTML pages for a front-end website or generate rich emails to send from an API. It provides an efficient way to write HTML code with minimal logic. We don’t need to write HTML code, Just leave that to Leaf. It supports Swift syntax, which can be easy to understand for iOS developers.</p><p>Let’s explore more about Leaf and try to build the first application using Leaf.</p><h3>How to Build Your First Application with Leaf</h3><p>Before we dive into creating a new project, we need to install some necessary tools on Xcode, which will be used to create a project environment.</p><p><strong>Vapor</strong></p><p>Vapor is a web framework for Swift that allows you to write backends, web app APIs, and HTTP servers in Swift. Vapor is written in Swift, which is a modern, powerful, and safe language, providing a number of benefits over the more traditional server languages.</p><p><strong>Steps to install Vapor on Mac OS are as follows:</strong></p><p>Now that you have Swift installed, let us install the <a href="https://github.com/vapor/toolbox">Vapor Toolbox</a>. This CLI tool is not required to use Vapor, but it includes helpful utilities like a new project creator.</p><p>The Toolbox is distributed via Homebrew. If you do not have Homebrew yet, visit <a href="https://brew.sh/">brew.sh</a> for install instructions.</p><pre>brew Install vapor</pre><p>Double check to ensure that the installation was successful by printing the help.</p><pre>vapor — help</pre><p>You should see a list of available commands.</p><h3>Start Building Your First Application</h3><p>First, you need to create a new directory for working on the Vapor project somewhere on your Mac.</p><p><strong>Steps to create a new directory:</strong></p><p>Open the terminal and follow the steps below.</p><pre>mkdir vaporProject<br>cd vaporProject</pre><p>This creates a new directory in your home folder called vaporProject and navigates you there.</p><p>Create a new project by following the command.</p><pre>vapor new HelloVapor</pre><p>While the execution of the above command will ask if you would like to use Leaf. Then type “y” in that case and press enter. Your project will be generated and it will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WDGs8u-T7yq3ygUb" /></figure><p>Now try to run an application using Xcode. Make sure you have created a custom working directory, otherwise Leaf won’t find your templates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WX3zgcfpau6088Cb" /></figure><p>You can also run the server using the command line as follows.</p><pre>swift run Run</pre><p>Enter <a href="http://localhost:8080/">http://localhost:8080</a> into your browser, where you will be able to check the output.</p><h3>Project Structure</h3><p>Let’s take a look at project folders and structures, which will help us to understand how they work.</p><p><strong>Package</strong></p><p>Find the package manifest file from the project and open it by double clicking. As you can see, the Leaf has been added as a dependency to the project.</p><pre>import PackageDescription<br>let package = Package(<br>    name: &quot;HelloVapor&quot;,<br>    platforms: [<br>        .macOS(.v10_15)<br>    ],<br>    dependencies: [<br>        /// Any other dependencies …<br>        .package(url: &quot;<a href="https://github.com/vapor/leaf.git">https://github.com/vapor/leaf.git</a>&quot;, from: &quot;4.0.0&quot;),<br>    ],<br>    targets: [<br>        .target(name: &quot;App&quot;, dependencies: [<br>            .product(name: &quot;Leaf&quot;, package: &quot;leaf&quot;),<br>            // Any other dependencies<br>        ]),<br>        // Other targets<br>    ]<br>)</pre><p><strong>Configuration</strong></p><p>After being added to the package, now you can start configuring vapor to use it. Check the <strong>Configure.swift</strong> file in the project, which will be as follows:</p><pre>import Leaf</pre><pre>app.views.use(.leaf)</pre><p>This tells Vapor to use the <strong>LeafRenderer</strong> when you call <strong>req.view</strong> in your code.</p><p><strong>Folder Structure</strong></p><p>After completion, configuration needs to ensure that you have a <strong>Views</strong> folder to store your.<strong>leaf</strong> files in. By default, <strong>the Views </strong>folder is at<strong>./Resources/Views</strong> relative to your project’s root.</p><p>The ideal flow would be as follows.</p><p>VaporApp<br>├── Package.swift<br>├── Resources<br>│ ├── Views<br>│ │ └── hello.leaf<br>├── Public<br>│ ├── images (images resources)<br>│ ├── styles (css resources)<br>└── Sources<br> └── …</p><p><strong>Rendering the View</strong></p><p>Now that Leaf is configured, let’s try to render a template. Create a new file called <strong>hello.leaf </strong>in <strong>./Resources/Views </strong>with the following content.</p><pre>Hello, #(name)!</pre><p>Then, register the route to render the view, which is generally done in the <strong>.swift </strong>file or in <strong>viewController</strong>. The content inside the router file looks as follows.</p><pre>app.get(“hello”) { req -&gt; EventLoopFuture&lt;View&gt; in<br> return req.view.render(“hello”, [“name”: “Leaf”])<br>}</pre><pre>// or</pre><pre>app.get(“hello”) { req async throws -&gt; View in<br> return try await req.view.render(“hello”, [“name”: “Leaf”])<br>}</pre><p>This uses the generic view property on request rather than calling Leaf directly.This allows you to switch between renderers.</p><p>Open your browser to <a href="http://localhost:8080/hello">http://localhost:8080/hello</a>, you should see <strong>hello, Leaf! </strong>On the console.</p><h3>Leaf Syntax Overview</h3><p>This is a basic information overview of leaf tag usage.</p><p>There are #count(users) users.</p><p>Leaf tags are made up of four elements, as below.</p><ul><li><strong>Token #</strong>: This signals the leaf parser to begin looking for a tag.</li><li><strong>Name count</strong>: That identifies the tag.</li><li><strong>Parameter List (users): </strong>May accept zero or more arguments.</li><li><strong>Body</strong>: An optional body can be supplied to some tags using a semicolon and a closing tag</li></ul><p>There are many different usage of Leaf tags based on implementation, let’s take a look at some built in tags explained in below examples.</p><pre>#(variable)<br>#extend(“template”): I’m added to a base template! #endextend<br>#export(“title”): Welcome to Vapor #endexport<br>#import(“body”)<br>#count(friends)<br>#for(friend in friends): &lt;li&gt;#(friend.name)&lt;/li&gt; #endfor</pre><p>Leaf also supports the below operators with which you are familiar in Swift.</p><ul><li>+(Plus)</li><li>%(Modulo)</li><li>&gt;(Greater than)</li><li>==(Equal to)</li><li>||(Logical OR)</li><li>etc.</li></ul><p>Examples of usage are as follows:</p><pre>#if(1 + 1 == 2):<br> Hello!<br>#endif</pre><pre>#if(index % 2 == 0):<br> This is even index.<br>#else:<br> This is odd index.<br>#endif</pre><p><strong>Context</strong></p><p>In the starting example, we took the [String: String] dictionary to pass data to the leaf. You can pass any <strong>encodable</strong> to the leaf. It’s actually preferred to use <strong>encodable</strong> structs since [String: Any] is not supported. This means you can not pass in an array.Let’s take a look at an example with struts.</p><p><strong>Swift file content looks like this:</strong></p><pre>struct WelcomeContext: Encodable {<br> var title: String<br> var numbers: [Int]<br>}<br>return req.view.render(“home”, WelcomeContext(title: “Hello!”, numbers: [42, 9001]))</pre><p><strong>Should rendered as below</strong></p><pre>&lt;h1&gt;#(title)&lt;/h1&gt;<br>#for(number in numbers):<br> &lt;p&gt;#(number)&lt;/p&gt;<br>#endfor</pre><h3>Usage of Some Common Tags</h3><h3>Conditions</h3><p>Leaf is able to evaluate conditions with the tag<strong> #if </strong>tag. Let’s look at some examples of how conditions can be evaluated.</p><p>Whether check variables exist or not, consider the below example.</p><pre>#if(title):<br> The title is #(title)<br>#else:<br> No title was provided.<br>#endif</pre><p>Compare with the custom string check in the below example.</p><pre>#if(title == “Welcome”):<br> This is a friendly web page.<br>#else:<br> No strangers allowed!<br>#endif</pre><p>If you want to use another tag as part of your condition, you should omit the <strong>#</strong> for the inner tag. You can also use <strong>#else </strong>Consider the following example:</p><pre>#if(title == “Welcome”):<br> Hello new user!<br>#elseif(title == “Welcome back!”):<br> Hello old user<br>#else:<br> Unexpected page!<br>#endif</pre><h3>Loops</h3><p>As you cannot provide an array directly to the leaf but you can manipulate each item by using the <strong>#for</strong> tag below, the example will help to understand.</p><p>For example, we could update our Swift code to provide a list of planets:</p><pre>struct SolarSystem: Codable {<br> let planets = [“Venus”, “Earth”, “Mars”]<br>}</pre><pre>return req.view.render(“solarSystem”, SolarSystem())</pre><p>We could then loop over them in Leaf like this:</p><p>Planets:</p><pre>&lt;ul&gt;<br>#for(planet in planets):<br> &lt;li&gt;#(planet)&lt;/li&gt;<br>#endfor<br>&lt;/ul&gt;</pre><p>This would render a view that looks like</p><pre>Planets:<br>- Venus<br>- Earth<br>- Mars</pre><h3>Extending templates</h3><p>Leaf’s <strong>#extend</strong> tag allows you to copy the contents of one template into another.</p><p>Extending is useful for copying in a standard piece of content, for example a page footer, advert code, or table that’s shared across multiple pages:</p><pre>#extend(“footer”)</pre><h3>Other tags</h3><p><strong>#count</strong></p><p>The #count tag returns the number of items in an array. For example:</p><pre>Your search matched #count(matches) pages.</pre><p><strong>#lowercased</strong></p><p>The #lowercased tag lowercases all letters in a string.</p><pre>#lowercased(name)</pre><p><strong>#uppercased</strong></p><p>The #uppercased tag uppercases all letters in a string.</p><pre>#uppercased(name)</pre><p><strong>#capitalized</strong></p><p>The #capitalized tag uppercases the first letter of each word in a string and lowercases the others.</p><pre>#capitalized(name)</pre><p><strong>#contains</strong></p><p>The #contains tag accepts an array and a value as its two parameters, and returns true if the array in parameter one contains the value in parameter two.</p><pre>#if(contains(planets, “Earth”)):<br> Earth is here!<br>#else:<br> Earth is not in this array.<br>#endif</pre><p><strong>#date</strong></p><p>The #date tag formats dates into a readable string. By default, it uses ISO8601 formatting.</p><pre>render(…, [“now”: Date()])</pre><pre>The time is #date(now)</pre><p>You can pass a custom date formatter string as the second argument.</p><pre>The date is #date(now, “yyyy-MM-dd”)</pre><p><strong>#unsafeHTML</strong></p><p>The #unsafeHTML tag acts like a variable tag-e.g., #(variable). However, it does not escape any HTML that variable may contain:</p><pre>The time is #unsafeHTML(styledTitle)</pre><h3>Custom Tags</h3><p>You can also create custom tags using the Leaf Tag protocol.</p><p>Let’s take a look at creating a custom tag <strong>#now</strong> that prints the current timestamp. The tag will also support a single, optional parameter for specifying the date format.</p><p><strong>LeafTag</strong></p><p>First, create a class called NowTag and conform it to LeafTag.</p><pre>struct NowTag: LeafTag {</pre><pre>   func render(_ ctx: LeafContext) throws -&gt; LeafData {<br>     …<br>   }<br>}</pre><p>Now let’s implement the render(_:) method. The LeafContext context passed to this method has everything we should need.</p><pre>struct NowTagError: Error {}<br>func render(_ ctx: LeafContext) throws -&gt; LeafData {<br>    let formatter = DateFormatter()<br>    switch ctx.parameters.count {<br>    case 0: formatter.dateFormat = &quot;yyyy-MM-dd HH:mm:ss&quot;<br>    case 1:<br>        guard let string = ctx.parameters[0].string else {<br>            throw NowTagError()<br>        }<br>        formatter.dateFormat = string<br>    default:<br>        throw NowTagError()<br>    }<br>    let dateAsString = formatter.string(from: Date())<br>    return LeafData.string(dateAsString)<br>}</pre><p><strong>Configure Tag</strong></p><p>Now that we’ve implemented NowTag, we just need to tell Leaf about it. You can add any tag like this-even if they come from a separate package. This is usually done in <strong>configure.swift</strong>:</p><pre>app.leaf.tags[“now”] = NowTag()</pre><p>And that’s it! We can now use our custom tag in Leaf.</p><pre>The time is #now()</pre><h3>Benefits</h3><ul><li>This framework is purely written in Swift so that iOS developers can take advantage of it and it is easy to understand.</li><li>It removes the dependency on third-party libraries where other frameworks may choose to implement things like Node.js’ HTTP parser, but it has its own Swift parser.</li><li>Leaf has the advantages of being natively Swift and being designed to integrate in a way that works well with Vapor’s engine, which is the underlying system that deals with requests and responses.</li></ul><h3>Conclusion</h3><p>This article provides a basic introduction to Leaf. As we can see, it supports Swift syntax, so it is easy to understand for any iOS developer, and with that we can create some server-side implementations and HTML templates. Though it has some limitations and scopes are limited currently, this basic overview will help to understand how Leaf will create templates. Hopefully, more scope and customization will be more useful to create dynamic HTML pages.</p><h3>Contributors</h3><p>I would like to give many thanks to <a href="https://medium.com/u/a2c1f661f6e2">Gopal Sorathiya</a> for finalising content for this article, and <a href="https://medium.com/u/53dd15a07de1">Jignesh Raiyani</a> for curating the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64ceb8fa3f54" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/introduction-to-the-leaf-in-ios-applications-64ceb8fa3f54">Introduction to Leaf for iOS</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>