简体   繁体   中英

Where do I put code that I need to run on all web pages in Play Framework?

I apologize in advance for this somewhat ignorant question, but I have researched this as much as possible on my own over the last week. My last resort was to come here because I know the folks on stack overflow are the smartest out there.

I'm an ASP.NET guy who recently switched over to Play, per company mandate. I'm a little lost. MVC is new to me, and ORM scares me entirely.

I've walked through the tutorials on playframework.org, and while I was able to build a blog engine, I was just transcribing code from their tutorial into my own program, so i don't feel like I really learned anything.

Now I'm having to write a PLay version of a .NET website. So onto my question.

On each webpage in my play app I need to run some Java code that generates a huge HTML string and then spit that html string onto a label on the view somewhere. It's like a 100 line function, and it just ends up returning a string that I render out to the client. In my .NET websites I just put this in the "code behind" of my master page.

The problem is that my master page in Play has no code-behind. So where do i put all this java code that needs to execute on every page? I started looking at controllers, but it's not an object that I would forward to the render function, it's a 100 line function that does a bunch of logic and returns a huge string. I need this code on every screen, so it doesn't make sense to put it at the controller level, because then I'd have to pass it to "render" every time, and I have like 100 actions.

Which really begs the bigger question, if your code isn't a model and doesn't really make sense in a controller, where do you stick it in Play? Anyway, thanks in advance.

Cheers Josh

I need this code on every screen, so it doesn't make sense to put it at the controller level, because then I'd have to pass it to "render" every time, and I have like 100 actions.

For these cases you can use the @Before annotation. In your controller:

@Before
public static void bigFunction() {
   String result;
   // Do a lot of stuff...
   renderArgs.put("yourLabel", result);
}

In your template you can access it now via:

${yourLabel}

I think Marius has the answer that you're looking for in the short term. But IMHO, you would do well by your successor (or yourself a year down the road) if you took the time to grok the function and re-implement it correctly into MVC components. That is, put the data representation and manipulation stuff into a model, and the HTML generation stuff into a view tag or the main.html template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM