Leaf in Vapor: Building Dynamic HTML with Swift
Yuriy Gudimov
iOS Developer | 3+ years | SwiftUI | UIKit | Combine | REST APIs | Vapor
In today's digital landscape, creating dynamic web applications is essential. For developers using Vapor, an efficient Swift web framework, Leaf is a powerful templating engine that allows you to generate HTML on the fly. In this article, we'll explore how to set up and use Leaf in your Vapor project, along with some more advanced examples to help you make the most of this templating language.
What is Leaf?
Leaf is a templating language inspired by Swift syntax that enables the generation of dynamic HTML pages. Whether you're building a front-end for your web application or need to send beautifully formatted emails, Leaf provides the tools you need.
Setting Up Leaf in Your Vapor Project
Step 1: Add Leaf as a Dependency
To start using Leaf, you'll need to add it to your project's Swift Package Manager (SPM) dependency list. Open your Package.swift file and include Leaf as shown below:
// swift-tools-version:5.8
import PackageDescription
let package = Package(
name: "MyApp",
platforms: [
.macOS(.v10_15)
],
dependencies: [
// Add Leaf as a dependency
.package(url: "https://github.com/vapor/leaf.git", from: "4.4.0"),
],
targets: [
.target(name: "App", dependencies: [
.product(name: "Leaf", package: "leaf"),
// Other dependencies can go here
]),
// Other targets
]
)
Step 2: Configure Leaf
Once you've added Leaf as a dependency, the next step is to configure it in the configure.swift file:
import Leaf
public func configure(_ app: Application) throws {
// Use Leaf as the View Renderer
app.views.use(.leaf)
}
This configuration tells Vapor to use the Leaf renderer whenever you call req.view in your routes.
Important Note:
Leaf comes with a caching system for performance optimization. In development mode, the cache is disabled to reflect template changes immediately. In production, you should restart your application to see changes made to templates.
Folder Structure
Make sure to create a directory structure that Vapor expects:
Place your .leaf files in the Resources/Views folder.
Rendering a Leaf View
Now that Leaf is correctly set up, let’s create our first dynamic web page.
Step 1: Create a Leaf Template
Create a file named hello.leaf in your Resources/Views folder with the following content:
Hello, #(name)!
领英推荐
Step 2: Set Up a Route
Next, you need to register a route to render this view. Open your routes.swift file and add the following code:
app.get("hello") { req -> EventLoopFuture<View> in
return req.view.render("hello", ["name": "Leaf"])
}
// Alternatively, using Swift's async/await syntax:
app.get("hello") { req async throws -> View in
return try await req.view.render("hello", ["name": "Leaf"])
}
Step 3: Test Your Setup
Now, run your Vapor application and visit /hello in your web browser. You should see the message "Hello, Leaf!" displayed. Congratulations, you've successfully rendered your first Leaf view!
Advanced Example: Conditional Rendering and Loops
One of the powerful features of Leaf is its ability to handle conditional rendering and loops, making it perfect for more complex pages.
Creating a List Template
Let's create another template called items.leaf that displays a list of items conditionally. Create items.leaf in your Resources/Views folder:
#if items.isEmpty
<p>No items found.</p>
#else
<ul>
#for item in items
<li>#(item)</li>
#endfor
</ul>
#end
Rendering the List
In your routes.swift, add the following route to render this list:
app.get("items") { req -> EventLoopFuture<View> in
let items = ["Apple", "Banana", "Cherry"]
return req.view.render("items", ["items": items])
}
// Alternatively, using Swift's async/await syntax:
app.get("items") { req async throws -> View in
let items = ["Apple", "Banana", "Cherry"]
return try await req.view.render("items", ["items": items])
}
Testing the List Route
Navigate to /items in your browser. You should now see a list of fruits rendered dynamically. If you were to pass an empty array, it would display "No items found."
Conclusion
Leaf is a powerful tool for creating dynamic HTML pages within your Vapor applications. In this article, we covered the basics of setting up Leaf and provided some advanced examples to showcase its capabilities. By leveraging Leaf, you can deliver rich, dynamic content to users with ease. Dive deeper into Leaf's documentation to explore more features and elevate your Vapor projects!
For more comprehensive information, I recommend checking out the official Vapor documentation.
Don’t forget to share your experiences with Leaf in the comments below and happy coding!
Very informative
Data Scientist with 5+ years of experience. Classical ML | Deep Learning | NLP | Recommender Systems.
3 个月Very clear article. Thank you so much for your work!
Front-End Developer | 3+ years | React, Redux, JavaScript/TypeScript
3 个月Seems like you've mastered vapor, great job!!!
PHP Developer 8+ years | Symfony, Laravel
3 个月Very informative, thanks