javacssjsdt

Writing css classes in java files


I need to format a static bit of headings that were coded within a java file as follows

public String getShortDescription() {

        if (code != null) {
            if (isOption1()) {
                return "Option 1 heading";          
            } else if (isOption2()) {
                return "Option2 heading";   
            } else if (isOption3()) {
                return "Option3 heading";   
            } else {
                return "";
            }
        } else {
            return "";
        }
    }

Is there a quick way to add css classes to the heading part i.e return "Option <span class="heading">1 heading</span>" ?


Solution

  • Normally it's bad to mix your data and display markup within your Java code. However, if there is no other workaround, then you could do the following:

    public static String wrapText(String text, String cssClass) {
        if (text == null) {
            throw new IllegalArgumentException("Text to wrap is null");
        }
        if (cssClass == null) {
            cssClass = "";
        }
        return "<span class=\"" + cssClass + "\">" + text + "</span>";
    }
    
    public String getShortDescription() {
        if (isOption1()) {
            return "Option " + wrapText("1 heading","heading");
        }
        ...
    }