Pages

Tuesday, May 28, 2013

CQ5/AEM how to create and use a custom taglib - part 1 create a custom tag.

The Problem

You want to create a custom taglib, and to have code complete in your target JSP file.

The Solution

In your taglib project, Add a new file called TestHeading.java, and include the following code:



package au.com.btes.tagexample;

import java.io.IOException;

import javax.servlet.jsp.JspException;

import com.cqblueprints.taglib.CqSimpleTagSupport;

/**
 * Example custom tag to show either content wrapped within a heading, or content wrapped within
 * a paragraph
 * @author bportier
 *
 */
public class CustomTag extends CqSimpleTagSupport {
private String content;
private boolean isHeading;

@Override
public void doTag() throws JspException, IOException {
String tagString="";

if(isHeading) {
tagString="h2";
}
else {
tagString="p";
}
String message="";
message=message.concat("<").concat(tagString).concat(">");
message=message.concat(content);
message=message.concat("</").concat(tagString).concat(">");
getJspWriter().write(message);
}

public String getContent(){
return content;
}

/**
* Defines the content that the tag will display
* @param content
*/
public void setContent(String content){
this.content=content;
}

public boolean getIsHeading(){
return isHeading;
}

/**
* Defines whether to display a heading (true) or a paragraph (false)
* @param isHeading
*/
public void setIsHeading(boolean isHeading){
this.isHeading=isHeading;
}
}



This has now created your custom tag.



No comments:

Post a Comment