Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import com.github.jknack.handlebars.Context
import com.github.jknack.handlebars.Helper
import com.github.jknack.handlebars.Options
/**
* filters a list and adds a variable to the context
*
* options:
* - assignTo: name of the variable to add to the context
* - field: (optional) filter by "trueness" of the given property (this is default)
* may start with an '!' to indicate inversion of trueness
*
* {{#findAll list field="name" assignTo="filteredList"}}
* {{#each filteredList}}
* ...
* {{/each}}
* {{/findAll}}
*
*
* {{#findAll list field="!this" assignTo="filteredList"}}
* {{#each filteredList}}.
* ...
* {{/each}}
* {{/findAll}}
*/
class FindAllHelper implements Helper<Collection<Object>> {
public static final String id = "findAll"
@Override
public CharSequence apply(Collection<Object> context, Options options) throws IOException {
def assignTo = (String) options.hash["assignTo"]
if (!assignTo) {
throw new IllegalArgumentException("assignTo not set")
}
def field = (String) options.hash("field", "this")
def negate = field.startsWith("!")
if (negate) {
field = field.substring(1)
}
def filtered = (context ?: []).findAll { isTrue(it, field, negate) }
return options.fn.apply(
Context.newBuilder(options.context, [(assignTo): filtered]).build()
)
}
private static boolean isTrue(Object value, String field, boolean negate) {
if (field == "this") {
field = null
}
def result = getField(value, field)
if (negate) {
return !result
} else {
return result
}
}
protected static Object getField(Object value, String field) {
if (field) {
return ((Map) value)[field]
} else {
return value
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.