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>

You'll probably want to look into Tiles.

EDIT: On a related note to tiles, you might want to look into Struts. It's not what you're looking for (that's tiles), but it is useful for someone coming from Django.


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.


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/

链接地址: http://www.djcxy.com/p/90128.html

上一篇: 如何在JSP页面中使用嵌入式代码生成可重用模板内容?

下一篇: JSP模板继承