Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSP template inheritance

Coming from a background in Django, I often use "template inheritance", where multiple templates inherit from a common base. Is there an easy way to do this in JSP? If not, is there an alternative to JSP that does this (besides Django on Jython that is :)

base template

<html>   <body>     {% block content %}     {% endblock %}   </body> <html> 

basic content

{% extends "base template" %} {% block content %} <h1>{{ content.title }} <-- Fills in a variable</h1> {{ content.body }} <-- Fills in another variable {% endblock %} 

Will render as follows (assuming that conten.title is "Insert Title Here", and content.body is "Insert Body Here")

<html>   <body>     <h1>Insert title Here <-- Fills in a variable</h1>     Insert Body Here <-- Fills in another variable   </body> <html> 
like image 837
Ryan Avatar asked Jan 29 '09 03:01

Ryan


2 Answers

You can do similar things using JSP tag files. Create your own page.tag that contains the page structure. Then use a <jsp:body/> tag to insert the contents.

like image 119
Ben Lings Avatar answered Oct 07 '22 08:10

Ben Lings


You can use rapid-framework for JSP template inheritance

base.jsp

%@ taglib uri="http://www.rapid-framework.org.cn/rapid" prefix="rapid" %>   <html>       <head>         <rapid:block name="head">             base_head_content         </rapid:block>     </head>       <body>           <br />           <rapid:block name="content">             base_body_content         </rapid:block>       </body>   </html> 

child.jsp

<%@ taglib uri="http://www.rapid-framework.org.cn/rapid" prefix="rapid" %>   <rapid:override name="content">        <div>         <h2>Entry one</h2>         <p>This is my first entry.</p>     </div> </rapid:override>    <!-- extends from base.jsp or <jsp:include page="base.jsp"> -->   <%@ include file="base.jsp" %>  

output

<html> <head>    base_head_content </head>   <body>       <br />       <div>         <h2>Entry one</h2>         <p>This is my first entry.</p>     </div> </body>   </html> 

source code

http://rapid-framework.googlecode.com/svn/trunk/rapid-framework/src/rapid_framework_common/cn/org/rapid_framework/web/tags/

like image 23
badqiu Avatar answered Oct 07 '22 08:10

badqiu