Thursday, March 23, 2023
HomeiOS DevelopmentWhat's new in Leaf 4 (Tau)?

What’s new in Leaf 4 (Tau)?


Every little thing you need to know concerning the upcoming Leaf template engine replace and migrate your Vapor / Swift codebase.

Vapor

Utilizing Leaf 4 Tau

Earlier than we dive in, let’s make a brand new Vapor mission with the next bundle definition.



import PackageDescription

let bundle = Bundle(
    title: "myProject",
    platforms: [
       .macOS(.v10_15)
    ],
    dependencies: [
        
        .package(url: "https://github.com/vapor/vapor.git", from: "4.30.0"),
        .package(url: "https://github.com/vapor/leaf", .exact("4.0.0-tau.1")),
        .package(url: "https://github.com/vapor/leaf-kit", .exact("1.0.0-tau.1.1")),
    ],
    targets: [
        .target(name: "App", dependencies: [
            .product(name: "Vapor", package: "vapor"),
            .product(name: "Leaf", package: "leaf"),
        ]),
        .goal(title: "Run", dependencies: ["App"]),
        .testTarget(title: "AppTests", dependencies: [
            .target(name: "App"),
            .product(name: "XCTVapor", package: "vapor"),
        ])
    ]
)


The very very first thing I might like to indicate you is that we have now a brand new render methodology. Up to now we have been in a position to make use of the req.view.render operate to render our template information. Think about the next actually easy index.leaf file with two context variables that we’ll give show actual quickly.


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta title="viewport" content material="width=device-width, initial-scale=1">
        <title>#(title)</title>
    </head>
    <physique>
        #(physique)
    </physique>
</html>

Now in our Vapor codebase we might use one thing like this to render the template.

import Vapor
import Leaf

public func configure(_ app: Utility) throws {

    app.views.use(.leaf)

    app.get() { req -> EventLoopFuture<View> in
        struct Context: Encodable {
            let title: String
            let physique: String
        }
        let context = Context(title: "Leaf 4", physique:"Whats up Leaf Tau!")
        return req.view.render("index", context)
    }
}

We will use an Encodable object and cross it round as a context variable. It is a handy manner of offering values for our Leaf variables. Earlier than we proceed I’ve to inform you that every one of this may proceed to work in Leaf Tau and you do not have to make use of the brand new strategies. 👍



New render strategies

So let me present you the very same factor utilizing the brand new API.

import Vapor
import Leaf

public func configure(_ app: Utility) throws {

    app.views.use(.leaf)

    app.get() { req -> EventLoopFuture<View> in
        let context: LeafRenderer.Context = [
            "title": "Leaf 4",
            "body": "Hello Leaf Tau!",
        ]
        return req.leaf.render(template: "index", context: context)
    }
}

That is not an enormous deal you could possibly say at first sight. Properly, the factor is that this new methodology offers type-safe values for our templates and that is simply the tip of the iceberg. You must neglect concerning the view property on the request object, since Leaf began to outgrow the view layer in Vapor.

import Vapor
import Leaf

public func configure(_ app: Utility) throws {

    app.views.use(.leaf)

    app.get() { req -> EventLoopFuture<View> in
        let title = "Leaf Tau"
        let context: LeafRenderer.Context = [
            "title": "Leaf 4",
            "body": .string("Hello (name)!"),
        ]
        return req.leaf.render(template: "index",
                               from: "default",
                               context: context,
                               choices: [.caching(.bypass)])
    }
}

In the event you take a more in-depth have a look at this comparable instance, you discover out that the context object and the values are representable by numerous sorts, but when we attempt to use an interpolated string, we have now to be somewhat bit extra sort particular. A LeafRenderer.Context object is considerably a [String: LeafData] alias the place LeafData has a number of static strategies to initialize the built-in primary Swift sorts for Leaf. That is the place the type-safety function is available in Tau. You need to use the static LeafData helper strategies to ship your values as given sorts. 🔨

The from parameter is usually a LeafSource key, in case you are utilizing a number of template areas or file sources then you’ll be able to render a view utilizing a particular one, ignoring the supply loading order. There’s one other render methodology with out the from parameter that’ll use the default search order of sources.


There’s a new argument that you should utilize to set predefined choices. You possibly can disable the cache mechanism with the .caching(.bypass) worth or the built-in warning message by means of .missingVariableThrows(false) if a variable shouldn’t be outlined in your template, however you are attempting to make use of it. You possibly can replace the timeout utilizing .timeout(Double) or the encoding through .encoding(.utf8) and grant entry to some nasty entities by together with the .grantUnsafeEntityAccess(true) worth plus there’s a embeddedASTRawLimit possibility. Extra about this afterward.


Additionally it is doable to disable Leaf cache globally by means of the LeafRenderer.Context property:

if !app.atmosphere.isRelease {
    LeafRenderer.Possibility.caching = .bypass
}

If the cache is disabled Leaf will re-parse template information each time you attempt to render one thing. Something that may be configured globally for LeafKit is marked with the @LeafRuntimeGuard property wrapper, you’ll be able to change any of the settings at utility setup time, however they’re locked as quickly as a LeafRenderer is created. 🔒




Context and knowledge illustration

You possibly can conform to the LeafDataRepresentable protocol to submit a customized sort as a context worth. You simply need to implement one leafData property.

struct Consumer {
    let id: UUID?
    let e-mail: String
    let birthYear: Int?
    let isAdmin: Bool
}
extension Consumer: LeafDataRepresentable {
    var leafData: LeafData {
        .dictionary([
            "id": .string(id?.uuidString),
            "email": .string(email),
            "birthYear": .int(birthYear),
            "isAdmin": .bool(isAdmin),
            "permissions": .array(["read", "write"]),
            "empty": .nil(.string),
        ])
    }
}

As you’ll be able to see there are many LeafData helper strategies to characterize Swift sorts. Each single sort has built-in optionally available help, so you’ll be able to ship nil values with out spending extra effort on worth checks or nil coalescing.

app.get() { req -> EventLoopFuture<View> in
    let person = Consumer(id: .init(),
                e-mail: "[email protected]",
                birthYear: 1980,
                isAdmin: false)

    return req.leaf.render(template: "profile", context: [
        "user": user.leafData,
    ])
}

You possibly can assemble a LeafDataRepresentable object, however you continue to have to make use of the LeafRenderer.Context as a context worth. Fortuitously that sort may be expressed utilizing a dictionary the place keys are strings and values are LeafData sorts, so this may scale back the quantity of code that you must sort.



Constants, variables, nil coalescing

Now let’s transfer away somewhat bit from Swift and discuss concerning the new options in Leaf. In Leaf Tau you’ll be able to outline variables utilizing template information with actual dictionary and array help. 🥳

#var(x = 2)
<p>2 + 2 = #(x + 2)</p>
<hr>
#let(person = ["name": "Guest"])
<p>Whats up #(person.title)</p>
<hr>
#(optionally available ?? "fallback")

Similar to in Swift, we are able to create variables and constants with any of the supported sorts. Once you inline a template variables may be accessed in each templates, that is fairly helpful as a result of you do not have to repeat the identical code repeatedly, however you should utilize variables and reuse chunks of Leaf code in a clear and environment friendly manner. Let me present you ways this works.

Additionally it is doable to make use of the coalescing operator to offer fallback values for nil variables.




Outline, Consider, Inline

One of many greatest debate in Leaf is the entire template hierarchy system. In Tau, your complete method is rebuilt below the hood (the entire thing is extra highly effective now), however from the end-user perspective only some key phrases have modified.




Inline

Lengthen is now changed with the brand new inline block. The inline methodology actually places the content material of a template into one other. You possibly can even use uncooked values in the event you do not need to carry out different operations (corresponding to evaluating Leaf variables and tags) on the inlined template.


<!-- index.leaf -->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta title="viewport" content material="width=device-width, initial-scale=1">
        <title>Leaf 4</title>
    </head>
    <physique>
        #inline("house", as: uncooked)
    </physique>
</html>

<!-- house.leaf -->
<h1>Whats up Leaf Tau!</h1>

As you’ll be able to see we’re merely placing the content material of the house template into the physique part of the index template.

Now it is extra attention-grabbing after we skip the uncooked half and we inline a daily template that accommodates different expressions. We’re going to flip issues just a bit bit and render the house template as a substitute of the index.


app.get() { req -> EventLoopFuture<View> in
    req.leaf.render(template: "house", context: [
        "title": "Leaf 4",
        "body": "Hello Leaf Tau!",
    ])
}


So how can I reuse my index template? Ought to I merely print the physique variable and see what occurs? Properly, we are able to attempt that…


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta title="viewport" content material="width=device-width, initial-scale=1">
        <title>#(title)</title>
    </head>
    <physique>
        #(physique)
    </physique>
</html>

<!-- house.leaf -->
<h1>Whats up Leaf Tau!</h1>
#inline("index")


Wait a minute… this code shouldn’t be going to work. Within the house template first we print the physique variable, then we inline the index template and print its contents. That is not what we wish. I need to use the contents of the house template and place it in between the physique tags. 💪





Consider

Meet consider, a operate that may consider a Leaf definition. You possibly can consider this as a block variable definition in Swift. You possibly can create a variable with a given title and afterward name that variable (consider) utilizing parentheses after the title of the variable. Now you are able to do the identical skinny in Leaf through the use of the consider key phrase or immediately calling the block like a operate.


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta title="viewport" content material="width=device-width, initial-scale=1">
        <title>#(title)</title>
    </head>
    <physique>
        #consider(bodyBlock) (# or you should utilize the `#bodyBlock()` syntax #)
    </physique>
</html>


On this template we are able to consider the bodyBlock and afterward we’ll be capable to outline it some place else.




Outline

Definitions. Lastly arrived to the final element that we’ll must compose templates. Now we are able to create our physique block within the house template.


#outline(bodyBlock):
<h1>#(physique)</h1>
#enddefine

#inline("index")

Now in the event you reload the browser (Leaf cache should be disabled) every part ought to work as it’s anticipated. Magic… or science, no matter, be happy to decide on one. 💫

Particular thanks goes to tdotclare who labored day and night time to make Leaf higher. 🙏

So what is going on on right here? The #outline(bodyBlock) part is chargeable for constructing a block variable known as bodyBlock that’s callable and we are able to consider it afterward. We merely print out the physique context variable inside this block, the physique variable is a context variable coming from Swift, that is fairly easy. Subsequent we inline the index template (think about copy-pasting whole content material of the index template into the house template) which is able to print out the title context variable and evaluates the bodyBlock. The bodyBlock shall be out there since we have simply outlined it earlier than our inline assertion. Simple peasy. 😝


<!-- var, let -->
#var(x = 10)
#let(foo = "bar")

<!-- outline -->
#outline(resultBlock = x + 1)
#outline(bodyBlock):
    <h2>Whats up, world!</h2>
    <p>I am a multi-line block definition</p>
#endblock

<!-- consider -->
#consider(resultBlock)
#bodyBlock()


I am actually glad about these modifications, as a result of Leaf is heading into the fitting path, and people individuals who haven’t used the pre-released Leaf 4 variations but these modifications will not trigger that a lot bother. This new method follows extra like the unique Leaf 3 habits.



Goodbye tags. Whats up entities!

Nothing is a tag anymore, however they’re separated to the next issues:

  • Blocks (e.g. #for, #whereas, #if, #elseif, #else)
  • Features (e.g. #Date, #Timestamp, and so forth.)
  • Strategies (e.g. .depend(), .isEmpty, and so forth.)

Now you can create your very personal capabilities, strategies and even blocks. 🔥

public struct Whats up: LeafFunction, StringReturn, Invariant {
    public static var callSignature: [LeafCallParameter] { [.string] }

    public func consider(_ params: LeafCallValues) -> LeafData {
        guard let title = params[0].string else {
            return .error("`Whats up` should be known as with a string parameter.")
        }
        return .string("Whats up (title)!")
    }
}

public func configure(_ app: Utility) throws {

    LeafConfiguration.entities.use(Whats up(), asFunction: "Whats up")
    
}

Now you should utilize this operate in your templates like this:

#Whats up("Leaf Tau")

You possibly can occasion overload the identical operate with totally different argument labels


public struct HelloPrefix: LeafFunction, StringReturn, Invariant {

    public static var callSignature: [LeafCallParameter] { [
        .string(labeled: "name"),
        .string(labeled: "prefix", optional: true, defaultValue: "Hello")]
    }

    public func consider(_ params: LeafCallValues) -> LeafData {
        guard let title = params[0].string else {
            return .error("`Whats up` should be known as with a string parameter.")
        }
        let prefix = params[1].string!
        return .string("(prefix) (title)!")
    }
}

public func configure(_ app: Utility) throws {


    LeafConfiguration.entities.use(Whats up(), asFunction: "Whats up")
    LeafConfiguration.entities.use(HelloPrefix(), asFunction: "Whats up")

    
}

This fashion you should utilize a number of variations of the identical performance.

#Whats up("Leaf Tau")
#Whats up(title: "Leaf Tau", prefix: "Hello")

Here is one other instance of a customized Leaf methodology:


public struct DropLast: LeafNonMutatingMethod, StringReturn, Invariant {
    public static var callSignature: [LeafCallParameter] { [.string] }

    public func consider(_ params: LeafCallValues) -> LeafData {
        .string(String(params[0].string!.dropLast()))
    }
}

public func configure(_ app: Utility) throws {

    LeafConfiguration.entities.use(DropLast(), asMethod: "dropLast")
    
}

You possibly can outline your individual Leaf entities (extensions) through protocols. You do not have to recollect all of them, as a result of there’s various them, however that is the sample that you need to search for Leaf*[Method|Function|Block] for the return sorts: [type]Return. If you do not know invariant is a operate that produces the identical output for a given enter and it has no unwanted effects.

You possibly can register these entities as[Function|Method|Block] by means of the entities property. It’ll take some time till you get conversant in them, however luckily Leaf 4 comes with fairly a superb set of built-in entities, hopefully the official documentation will cowl most of them. 😉

public struct Path: LeafUnsafeEntity, LeafFunction, StringReturn {
    public var unsafeObjects: UnsafeObjects? = nil

    public static var callSignature: [LeafCallParameter] { [] }

    public func consider(_ params: LeafCallValues) -> LeafData {
        guard let req = req else { return .error("Wants unsafe entry to Request") }
        return .string(req.url.path)
    }
}


public func configure(_ app: Utility) throws {

    LeafConfiguration.entities.use(Path(), asFunction: "Path")

    
}

Oh, I virtually forgot to say that in the event you want particular entry to the app or req property you must outline an unsafe entity, which shall be thought of as a nasty apply, however luckily we have now one thing else to switch the necessity for accessing these items…



Scopes

If it’s essential to cross particular issues to your Leaf templates it is possible for you to to outline customized scopes.

extension Request {
    var customLeafVars: [String: LeafDataGenerator] {
        [
            "url": .lazy([
                        "isSecure": LeafData.bool(self.url.scheme?.contains("https")),
                        "host": LeafData.string(self.url.host),
                        "port": LeafData.int(self.url.port),
                        "path": LeafData.string(self.url.path),
                        "query": LeafData.string(self.url.query)
                    ]),
        ]
    }
}
extension Utility {
    var customLeafVars: [String: LeafDataGenerator] {
        [
            "isDebug": .lazy(LeafData.bool(!self.environment.isRelease && self.environment != .production))
        ]
    }
}

struct ScopeExtensionMiddleware: Middleware {

    func reply(to req: Request, chainingTo subsequent: Responder) -> EventLoopFuture<Response> {
        do {
            attempt req.leaf.context.register(mills: req.customLeafVars, toScope: "req")
            attempt req.leaf.context.register(mills: req.utility.customLeafVars, toScope: "app")
        }
        catch {
            return req.eventLoop.makeFailedFuture(error)
        }
        return subsequent.reply(to: req)
    }
}

public func configure(_ app: Utility) throws {

    app.middleware.use(ScopeExtensionMiddleware())

    
}

Lengthy story quick, you’ll be able to put LeafData values right into a customized scope, the good factor about this method is that they are often lazy, so Leaf will solely compute the corresponding values if when are getting used. The query is, how will we entry the scope? 🤔

<ul>
    <li><b>ctx:</b>: #($context)</li>
    <li><b>self:</b>: #(self)</li>
    <li><b>req:</b>: #($req)</li>
    <li><b>app:</b>: #($app)</li>
</ul>

You must know that self is an alias to $context, and you’ll entry your individual context variables utilizing the $ signal. You too can construct your individual LeafContextPublisher object that may use to change the scope.


ultimate class VersionInfo: LeafContextPublisher {

    let main: Int
    let minor: Int
    let patch: Int
    let flags: String?

    init(main: Int, minor: Int, patch: Int, flags: String? = nil) {
        self.main = main
        self.minor = minor
        self.patch = patch
        self.flags = flags
    }

    var versionInfo: String {
        let model = "(main).(minor).(patch)"
        if let flags = flags {
            return model + "-" + flags
        }
        return model
    }

    lazy var leafVariables: [String: LeafDataGenerator] = [
        "version": .lazy([
            "major": LeafData.int(self.major),
            "minor": LeafData.int(self.minor),
            "patch": LeafData.int(self.patch),
            "flags": LeafData.string(self.flags),
            "string": LeafData.string(self.versionInfo),
        ])
    ]
}

public func configure(_ app: Utility) throws {

    app.views.use(.leaf)

    app.middleware.use(LeafCacheDropperMiddleware())

    app.get(.catchall) { req -> EventLoopFuture<View> in
        var context: LeafRenderer.Context = [
            "title": .string("Leaf 4"),
            "body": .string("Hello Leaf Tau!"),
        ]
        let versionInfo = VersionInfo(main: 1, minor: 0, patch: 0, flags: "rc.1")
        attempt context.register(object: versionInfo, toScope: "api")
        return req.leaf.render(template: "house", context: context)
    }

    

}

What if you wish to lengthen a scope? No drawback, you are able to do that by registering a generator

extension VersionInfo {

    var extendedVariables: [String: LeafDataGenerator] {[
        "isRelease": .lazy(self.major > 0)
    ]}
}



let versionInfo = VersionInfo(main: 1, minor: 0, patch: 0, flags: "rc.1")
attempt context.register(object: versionInfo, toScope: "api")
attempt context.register(mills: versionInfo.extendedVariables, toScope: "api")
return req.leaf.render(template: "house", context: context)


There’s an app and req scope out there by default, so you’ll be able to lengthen these by means of an extension that may return a [String: LeafDataGenerator] variable.




Abstract

As you’ll be able to see Leaf improved rather a lot in comparison with the earlier variations. Even within the beta / rc interval of the 4th main model of this async template engine introduced us so many nice stuff.

Hopefully this text will make it easier to through the migration course of, and I imagine that it is possible for you to to make the most of most of those built-in functionalities. The model new render and context mechanism provides us extra flexibility with out the necessity of declaring extra native buildings, Leaf variables and the redesigned hierarchy system will help us to design much more highly effective reusable templates. By entity and the scope API we can carry Leaf to a totally new stage. 🍃



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments