1 52 53 package freemarker.core; 54 55 import freemarker.template.*; 56 import java.io.*; 57 58 final class StringLiteral extends Expression implements TemplateScalarModel { 59 60 private final String value; 61 private TemplateElement interpolatedOutput; 62 63 StringLiteral(String value) { 64 this.value = value; 65 } 66 67 void checkInterpolation() throws ParseException { 68 if (value.indexOf("${") >= 0 || value.indexOf("#{") >= 0) { 69 SimpleCharStream scs = new SimpleCharStream(new StringReader(value), beginLine, beginColumn+1, value.length()); 70 FMParserTokenManager token_source = new FMParserTokenManager(scs); 71 token_source.onlyTextOutput = true; 72 FMParser parser = new FMParser(token_source); 73 parser.template = getTemplate(); 74 interpolatedOutput = parser.FreeMarkerText(); 75 this.constantValue = null; 76 } 77 } 78 79 TemplateModel _getAsTemplateModel(Environment env) throws TemplateException { 80 return new SimpleScalar(getStringValue(env)); 81 } 82 83 public String getAsString() { 84 return value; 85 } 86 87 String getStringValue(Environment env) throws TemplateException { 88 if (interpolatedOutput == null) { 89 return value; 90 } 91 else { 92 TemplateExceptionHandler teh = env.getTemplateExceptionHandler(); 93 env.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); 94 try { 95 return env.renderElementToString(interpolatedOutput); 96 } 97 catch (IOException ioe) { 98 throw new TemplateException(ioe, env); 99 } 100 finally { 101 env.setTemplateExceptionHandler(teh); 102 } 103 } 104 } 105 106 public String getCanonicalForm() { 107 return "\"" + escapeString(value) + "\""; 109 } 110 111 boolean isLiteral() { 112 return interpolatedOutput == null; 113 } 114 115 Expression _deepClone(String name, Expression subst) { 116 StringLiteral cloned = new StringLiteral(value); 117 cloned.interpolatedOutput = this.interpolatedOutput; 118 return cloned; 119 } 120 121 static private String escapeString(String s) { 122 if (s.indexOf('"') == -1) { 123 return s; 124 } 125 java.util.StringTokenizer st = new java.util.StringTokenizer (s, "\"", true); 126 StringBuffer buf = new StringBuffer (); 127 while (st.hasMoreTokens()) { 128 String tok = st.nextToken(); 129 if (tok.equals("\"")) { 130 buf.append('\\'); 131 } 132 buf.append(tok); 133 } 134 return buf.toString(); 135 } 136 } 137 | Popular Tags |