Portlet edit CSS style

September 10, 2008 · Posted in Portlet · Comment 

Working with portlet development can be challenging, because the portal might or might not help you with routine stuff. A portlet goes through several modes. The normal mode is the View mode which shows the content. Another mode is Action, where the portlat receives request parameters and performs some action of it. The mode of interest in this blog entry, is the Edit mode. This mode is used to configure the portlet, or to be more exact, show a configuration form, which then is submitted into the action mode (processAction).

When you want to configure the portlet, the administrator clicks the edit button of the portal to show the edit form of the portlet in question. The result is a popup window with the content. It shows a complete HTML document, where the portlet form is just a subarea.  Now, here is the catch.

  • You want to apply some CSS styles.
  • You do not want to use inline styles, i.e., <tag style=”…”
  • You want to import an external CSS fil, so you can apply a consistent look&feel
  • The style directive must be placed in the head section, not in the body section
  • The HTML emitted by the portlet goes only somewhere into the body area

The solution is to use some a JavaScript snippet to inject the CSS imports into the head DOM. Thankfully, the HTML standard allows script tags to appear in the body. The JS snippet need to be evaluated, after the document has loaded and then modify the DOM. At this time I had just started to investigate jQuery a great JS library. So the snippet below is using the support of jQuery instead of brute-force JavaScript.

Put this snippet at the top of the dispatched JSP from a portlet’s doEdit().

<c:set var="webapp" value="${renderRequest.contextPath}" />
<script type="text/javascript" src="${webapp}/js/jquery-1.2.6.js"></script>
<script>
    $("<style type='text/css'> @import '${webapp}/css/portlet_edit.css'; </style>").appendTo("head");
</script>

As you can see, it relies on the JavaScript files being put into the /js/ directory and the CSS files into the /css/ directory, both at the top of the WAR file content.