I’m looking to properly factor my views, to not generate much duplication. I’m using the Play framework, and the elements I’d like to factor out are basic common ones – headers, footers, navigation elements.
What is the standard pattern for this type of factoring? When I read about the view inheritance features, they sound as if they don’t allow for reuse of components.
I’m working with version 2.0 of Play.
Say, for example, that I have a common layout for multiple pages, and I’m looking to have swappable bits – say, the central content bit, and the footer, where different pages I’m displaying have different combinations of footer and content.
You should use combination of
layoutsandtagsas described in the documentation.Layoutwraps current view, so it’s best place for starting and ending the HTML structure, adding scripts intoheadsection of the hTML doc, and placing typical elements – such as stable header with logo, footer with copyrights etc. If you have the same main navigation on all pages, you can put it in layout too, then you can add params to the layout view to make it possible easily changing CSS classes for the active item. Note, that if you have for an example 2 different versions of main nav (for an example, one for common users, second for administrators only), you can just create 2 different layouts or use one layout and display two different versions depending on some param passed from the initial view.Tagsare used for injecting code into current view (so they has just opposite role than layouts). They are a common views without layout, and are functions with params too. They are used mainly for placing things that are changing on every page or even request – for an example notice boxes (from the doc:success,error, etc). Also they are useful for subnavigation, especially, when it’s changes on every ‘branch’ from main navigation and it’s possible, that on some pages it should not be displayed at all.You can also use
tagsin thelayouts(and probably, vice versa) so as you can see, there are many possibilities 🙂Note: palako’s sample illustrates it quite well, but it’s typical for Play 1.x templating engine, for Play 2.x check referenced documentation and/or sample application delivered with the source of Play.