groue / GRMustache.swift

Flexible Mustache templates for Swift
http://mustache.github.com/
MIT License
601 stars 154 forks source link

Zero-parameter filters #29

Closed edwardaux closed 8 years ago

edwardaux commented 8 years ago

Firstly, let me say thanks so much for this project. Soooooo good!

I've been adding my own custom filters, and I want to add one that I can call like: randomNumber(), however, it doesn't look like GRMustache supports filters with zero parameters.

I thought I'd be able to use something like:

let filter = VariadicFilter { (boxes: [MustacheBox]) in
    let randomNumber = generateRandomNumber()
    return Box(randomNumber)
}
template.registerInBaseContext("randomNumber", Box(filter))

and invoke using {{ randomNumber() }}, however, my filter never gets invoked. If, however, I use {{ randomNumber(XXX) }} where XXX is anything at all (a variable that doesn't exist, a ., whatever), then my filter gets invoked.

I tried just using a normal Filter too, but that doesn't get invoked either. Any thoughts?

groue commented 8 years ago

Hello @edwardaux. I admit that zero-parameter filters look like they are missing, and it can be argued that they do.

Yet, you can still produce a random number generator. It's not a filter (which transforms a value into another), but instead a kind of lambda, a function that provides custom rendering:

let randomRenderer = { (info: RenderingInfo) -> Rendering in
    // Generate a random number, and render just what this number would render:
    let number = UInt(arc4random())
    return try Box(number).render(info: info)
}

let template = try! Template(string: "Hello {{ rand }} {{ rand }} {{ rand }}")
let rendering = try! template.render(Box(["rand": Box(randomRenderer)]))
print(rendering)

Is it a solution to your need?

edwardaux commented 8 years ago

Thanks for the feedback. That is actually perfect (and in fact, conceptually, more correct to my mind). Thanks for the suggestion. Works perfectly.

groue commented 8 years ago

Glad you like it! Happy Mustache!