AndresQ
AndresQ

Reputation: 803

after-action-before-render kind of interceptor (Play 1.x)

I know of the existence of @Before and @After, but @After happens to execute after the rendering of the template

Almost all my controllers extends a specific class of mine, and I want to, unobtrusively, be able to execute some code in my super class that checks for some conditions and sets some flash/renderArgs after the execution of the code in the subclass, but before the rendering is done

any simple way to achieve this?

edit: here's a snippet of the code

class MyController extends Controller {
   @After
   static void checkStage() {
      if (xyz) {
         flash.put("stage", "bla");
      }
   }
}

my controllers all extend MyController but since the checkStage code is called AFTER the rendering is done, the stage flash attribute will be rendered the next time a page is rendered

Actually, I would want to use flash.now instead of flash.put, but because the code @After code is executed after the rendering, it never shows up

Upvotes: 5

Views: 858

Answers (2)

Tom Carchrae
Tom Carchrae

Reputation: 6476

Well, if you want simplest: just insert the check code before you call render(). That is the most simple approach!

If you want something more complex, you could make a Plugin that overrides loadTemplate https://github.com/playframework/play/blob/master/framework/src/play/PlayPlugin.java#L157 and wraps the Template returned with your extra code. The other part of this you need to look at is the template loader: https://github.com/playframework/play/blob/master/framework/src/play/templates/TemplateLoader.java#L58 - Seems awfully convoluted, but could work.

Maybe you should explain why you are trying to do this pre-render code - there could be a better approach.


Edit: Ok, I see what you are trying to do. Yes, once the request is sent, you cannot modify cookies (aka flash). I'd suggest you avoid using cookies to maintain state between transactions - each variable adds to the HTTP transaction and is sent on every request.

Instead, I suggest you use Cache.set(Session.getId(), map) and put all the state values in the Map. Then I think you can save them during an @After

Example here; http://www.playframework.com/documentation/1.2.5/controllers#session

Upvotes: 2

Pere Villega
Pere Villega

Reputation: 16439

DISCLAIMER: it's been a while since I've used Play 1.x, take it with a grain of salt

If I understand you want to do something like:

public static void myMethod() {
   // myMethod code here

   // some common code here

   renderTemplate("myTemplate.html", id, client);
}

You should be able to extract this common part onto your parent controller to a method like:

public static void renderMyTemplate(String template, Object... params){
   // some common code here
   renderTemplate(template, params);
}

and replace your calls to renderby calls to this method. This should tackle your issue.

Upvotes: 0

Related Questions