Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

java - JSP, can it work similar to yield, layout, content_for in Ruby/Rails/Erb

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...