Created
May 30, 2016 15:01
-
-
Save christoph-daehne/95fedde7abdac394f0566980f7d10938 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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