leaf-kit icon indicating copy to clipboard operation
leaf-kit copied to clipboard

`requireBody()` and `requireNoBody()` not working as expected

Open ptoffy opened this issue 2 years ago • 0 comments

Describe the bug

Whilst creating a custom UnsafeUnescapedLeafTag, context.requireNoBody() always throws even if no body is provided, while context.requireBody() never throws even when no body is provided, rather returning an empty [Syntax].

While looking through the tests I noticed these methods are not tested anywhere and I think simply checking for the array being empty in addition to checking for it being != nil could solve the issue. The other option would be searching where the body of the tag is passed in and setting it to nil if it's an empty array

To Reproduce

  1. Create a simple project just using Leaf 4
  2. Create
struct BodyRequiringTag: UnsafeUnescapedLeafTag {
    func render(_ ctx: LeafContext) throws -> LeafData {
        _ = try ctx.requireBody()
        
        return .string("Hello there")
    }
}

and

struct NoBodyRequiringTag: UnsafeUnescapedLeafTag {
    func render(_ ctx: LeafContext) throws -> LeafData {
        try ctx.requireNoBody()
        
        return .string("General Kenobi")
    }
}
  1. Add the tags to the test project
app.leaf.tags["bodytag"] = BodyRequiringTag()
app.leaf.tags["nobodytag"] = NoBodyRequiringTag()
  1. Adding the first tag to the project
#bodytag:#endbodytag

or

#bodytag()

This returns Hello there, which is just the return type of the tag, while it should be returning {error: true, reason: "Missing body"

  1. Adding the other tag
#nobodytag

This returns {error: true, reason: "Extraneous body"} The only way to make this error go away is to set the template as

#nobodytag:#endnobodytag

Which is, I think, not that intuitive

Environment

  • Vapor Framework version: 4.76.0
  • Vapor Toolbox version: 18.6.0
  • OS version: MacOS Ventura 13.0
  • Xcode version: 14.1 (14B47b)

ptoffy avatar Apr 20 '23 08:04 ptoffy