10

I am trying to figure out how to most effectively reuse JSP code. I love the way Rails/erb works in that way ... with yield, layout, content_for

Example:

main_layout.erb.html

<html>
  <head><%= yield :head %></head>
  <body><%= yield %></body>
</html>

use

<% content_for :head do %>
<title>A simple page</title>
<% end %>

<p>Hello, Rails!</p>

in controller

layout "main_layout"

What is the closest I can get to this with JSP (without using extra frameworks)? I know about JSP include but that's not really the same as yield. Any suggestions?

Thanks

bob
  • 103
  • 1
  • 4
  • 1
    JSP's got nothin' on ERB. It does little more than give you some custom tags and allow you to interact with your model object. You can leverage more power by returning a JSON object and doing JavaScript widgeting, as far as I'm concerned. – Samo Dec 03 '10 at 17:56
  • Another great JSP tag files answer is https://stackoverflow.com/a/3257426/37572 – John Rees Mar 08 '18 at 21:13

2 Answers2

17

I'm not familiar with what yield and content_for provide, but JSP tag files allow you a more robust way to template pages than JSP includes.

Example:

layout.tag

<%@ tag body-content="scriptless" %>
<%@ attribute name="pageTitle" required="true" type="java.lang.String" %>

<html>
<head>
    <title>${pageTitle}</title>
</head>
<body>
    <jsp:doBody/>
</body>
</html>

An individual JSP

<%@ taglib prefix="z" tagdir="/WEB-INF/tags" %>
<z:layout pageTitle="A simple page">
    <p>Hello, JSP!</p>
</z:layout>

Just place your layout.tag in the /WEB-INF/tags directory. You can use any available prefix you want, I just used "z" for the example.

Steven Benitez
  • 10,936
  • 3
  • 39
  • 50
0

While you mentioned wanting no frameworks on top of stock jsp, the Layout functionality of the Stripes Framework does pretty much exactly what you're asking for.

Ophidian
  • 9,775
  • 2
  • 29
  • 27