Nick
Nick

Reputation: 5200

Vapor/Leaf Custom Tag not returning correct value

I have registered a custom tag to return true if the index is odd and false if even as follows:

class OddEvenTag: BasicTag {
    let name = "OddEven"

    func run(arguments: ArgumentList) throws -> Node? {
        guard
            arguments.count == 1,
            let index = arguments[0]?.int
            else { return Node(nil) }
        print(index, index & 1)
        return Node((index & 1) == 1)
    }
}

The print statement produces satisfyingly good output:

0 0
1 1
2 0
3 1
...

However, when I use the custom tag inside a #loop in a leaf file, such as

#OddEven(offset){hello}##else(){bye}

It always instantiates the hello. I've tried hard-coding false into the return statement and it doesn't change the outcome. I have used a (more complex) custom tag before, so I know they can work.

In case you're wondering, I really want to use the tag to alternate the row background colours of a grid!

Upvotes: 3

Views: 292

Answers (1)

tobygriffin
tobygriffin

Reputation: 5421

A BasicTag can only be used like this:

#TagName(variable)

and returns a value.

If you want to conditionally render a following block like this:

#TagName(variable) { show if true }

then you need to extend Tag, and put your show/hide code in the shouldRender(tagTemplate:arguments:value:) function.

As a starting point, look at the If tag, but instead of testing for true values, test for even values.

Upvotes: 1

Related Questions