开发者

Play! How to retrieve field value in a template tag having entity and the field name passed separately as parameters?

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 her开发者_运维问答e. 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.


For me it works with easy way. I have pager tag:

#{pager model:productList, totalCount:total /}

And in pager.tag i have:

<div class="total">${_totalCount}</div>
<ul>
#{list items:_model.getStartPage(params.pageNumber).._model.getPageCount(params.pageNumber), as:'i'}
%{selectedClass=i.toString()==(params.pageNumber==null? "1" : params.pageNumber)?"selected":""%}
<li class="${selectedClass}">
    #{if selectedClass == "selected"}
    <span>${i}</span>
    #{/if}
    #{else}
    <a href="@{Product.list(params.categoryId, params.rangeStart, params.rangeEnd, params.brandId, i, params.pageSize, params.q)}">${i}</a>
    #{/else}
</li>
#{/list}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜