Reputation: 2993
What are some ways (if any) to link or import a style sheet from a JSP tag called in the <body>? It would be great if I can encapsulate all necessary imports in the JSP tag.
index.jsp:
<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="x" tagdir="/WEB-INF/tags" %>
<html>
<head>
<!-- we have to know what css file somecontent uses and include it here -->
<!-- the tag below prints <link rel="/somecontent.css"... /> but makes sure this url is only included once -->
<x:requireOnce loc="/somecontent.css" type="css" />
</head>
<body>
<x:somecontent />
</body>
</html>
index.jsp:
<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="x" tagdir="/WEB-INF/tags" %>
<html>
<head>
<%-- nothing for somecontent tag here --%>
</head>
<body>
<x:somecontent />
...
</body>
</html>
somecontent.tag:
<%@ tag description="some independent content" %>
<%@ taglib prefix="x" tagdir="/WEB-INF/tags" %>
<%-- the inline attribute will indicate that it is in the body and shouldn't use <link> which won't work here --%>
<x:requireOnce loc="/somecontent.css" type="css" inline="true" />
<%-- this will print <script type="text/javascript" src="/somecontent.js" ...></script> --%>
<x:requireOnce loc="/somecontent.js" type="js" />
...
Is there a way to keep a reference to the position in the head tag within the JspWriter and insert content there when necessary, i.e. new link tags?
Ideally, I don't want to inline the contents of the stylesheet or use javascript to include the style sheet. Hopefully there's some way with @import, <link> or some JSP magic... Thoughts?
Upvotes: 2
Views: 2384
Reputation: 692261
You could do something along the lines of what SiteMesh does.
Each requireOnce
tag would just put the file to link to in a list of files, stored in a request attribute. A servlet filter would buffer the whole response, and rewrite it when completed with the head section rewritten to include all the links.
Upvotes: 1