Tuesday, December 23, 2014
Custom Taglib in Liferay 6.2
Hi! This is the example of a custom tag created inside a portlet plugin in Liferay 6.2. To create a custom taglib in Liferay is fairly easy, so let's start!
First, we have to create the XML where we will define the new tag. In this case we will create a file named MyTags.tld, stored in the folder WEB-INF/src/META-INF.
The tag name will be "custom", and it will have two attributes, one of them compulsory.
The code for this file is the following:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>example</shortname>
<uri>http://rlopez.es/tld</uri>
<info>Custom tag</info>
<tag>
<name>custom</name>
<tagclass>com.rlopez.tags.CustomTag</tagclass>
<bodycontent>empty</bodycontent>
<info>Custom Tag</info>
<attribute>
<name>attribute1</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>attribute2</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
Once we have created the new tag "custom" with its parameters, we'll have to create the class to "paint" the tag, It can be done in several ways, but the most straightforward is to extend the class "TagSupport". We must provide two methods to set the parameters values and the two methods "doStartTag" and "doEndTag".
The class will turn out like this:
public class CustomTag extends TagSupport{
private String attribute1="";
private String attribute2="";
public void setAttribute1(String s) {
attribute1 = s;
}
public void setAttribute2(String s) {
attribute2 = s;
}
public int doStartTag() throws JspException {
try{
String s="";
s+="<div class='customTagDiv'>";
s+="<strong> "+attribute1+ " " +attribute2+" </strong>";
s+="</div>";
pageContext.getOut().print( s );
} catch (Exception e) {
throw new JspException ("Error: IOException" + e.getMessage());
}
return SKIP_BODY;
}
public int doEndTag() throws JspException {
return SKIP_PAGE;
}
}
And finally, we can already use our new tag in a jsp file:
<%@ taglib uri="http://rlopez.es/tld" prefix="rls" %>
<rls:custom attribute1="Ruben" attribute2="Lopez"/>
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment