I wanted to create a tag like:
#{some_tag entity:user, field:'name'}
and expect it to produce some output with the user name in it by using expression like:
${_entity._field}
I know it doesn't work but that's why I ask here. Is there a simple way to use a field name passed as a parameter to a template tag to get the field value?
When I needed to do this I did something similar to the CRUD module. I call the tag as #{sometag 'entity.field' /}
then in the fast tag I have (roughly):
String[] parts = args.get("arg").split("\\.");
Object entity = play.mvc.Scope.RenderArgs.current().get(parts[0]);
String field = String.valueOf(parts[1]);
Object value = groovy.util.Eval.me("_caller", template.template, "_caller." + args.get("arg").replace(".", "?."));
I am not aware of an easy answer, but it is possible. You can create a fast tag, and use reflection to get the field you are after. You can get more info on Fast Tags here - Can someone explain how to use FastTags
However, wouldnt it be easier to just send the specific field through to your tag?
The parameters are stored in a variable called renderArgs. I'm not sure if this is directly accessible inside templates, but if this doesn't work:
renderArgs.get(_entity)
then you can probably access it indirectly using the static method:
Scope.RenderArgs.current().get(_entity)
Accessing a named field of that entity is then a matter of reflection.
However, I agree with the suggestion that there has to be an easier way. If you find yourself doing reflection like that, it usually (not always) means you've over-engineered something.
You could just pass those parameters to a utility class that uses reflection to find the String value you actually want displayed.
${play.sample.util.ReflectUtil.get(_entity, _field)}
play.sample.util.ReflectUtil:
public static String get(String entity, String field) {
String displayValue = ... // look up value ...
return displayValue;
}
Or a FastTag would work too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With