1 52 53 package freemarker.core; 54 55 import java.io.IOException ; 56 import java.io.StringWriter ; 57 import java.io.Writer ; 58 import java.util.Map ; 59 60 import freemarker.template.SimpleScalar; 61 import freemarker.template.TemplateException; 62 import freemarker.template.TemplateModel; 63 import freemarker.template.TemplateTransformModel; 64 65 68 final class BlockAssignment extends TemplateElement { 69 70 private final String varName; 71 private final Expression namespaceExp; 72 private final int scope; 73 74 BlockAssignment(TemplateElement nestedBlock, String varName, int scope, Expression namespaceExp) { 75 this.nestedBlock = nestedBlock; 76 this.varName = varName; 77 this.namespaceExp = namespaceExp; 78 this.scope = scope; 79 } 80 81 void accept(Environment env) throws TemplateException, IOException { 82 if (nestedBlock != null) { 83 env.visit(nestedBlock, new CaptureOutput(env), null); 84 } 85 } 86 87 private class CaptureOutput implements TemplateTransformModel { 88 private final Environment env; 89 private final Environment.Namespace fnsModel; 90 91 CaptureOutput(Environment env) throws TemplateException { 92 this.env = env; 93 TemplateModel nsModel = null; 94 if(namespaceExp != null) { 95 nsModel = namespaceExp.getAsTemplateModel(env); 96 if (!(nsModel instanceof Environment.Namespace)) { 97 throw new TemplateException( 98 "namespace parameter does not specify " 99 + "a namespace. It is a " 100 + nsModel.getClass().getName(), env); 101 } 102 } 103 fnsModel = (Environment.Namespace )nsModel; 104 } 105 106 public Writer getWriter(Writer out, Map args) { 107 return new StringWriter () { 108 public void close() { 109 SimpleScalar result = new SimpleScalar(toString()); 110 switch(scope) { 111 case Assignment.NAMESPACE: { 112 if(fnsModel != null) { 113 fnsModel.put(varName, result); 114 } 115 else { 116 env.setVariable(varName, result); 117 } 118 break; 119 } 120 case Assignment.LOCAL: { 121 env.setLocalVariable(varName, result); 122 break; 123 } 124 case Assignment.GLOBAL: { 125 env.setGlobalVariable(varName, result); 126 break; 127 } 128 } 129 } 130 }; 131 } 132 } 133 134 public String getCanonicalForm() { 135 String key; 136 switch(scope) { 137 case Assignment.LOCAL: { 138 key = "local"; 139 break; 140 } 141 case Assignment.GLOBAL: { 142 key = "global"; 143 break; 144 } 145 default: { 146 key = "assign"; 147 break; 148 } 149 } 150 return "<#" + key + " " + varName + 151 (namespaceExp != null ? " in " + namespaceExp.getCanonicalForm() : "") 152 + ">" + nestedBlock.getCanonicalForm() + "</#" + key + ">"; 153 } 154 155 public String getDescription() { 156 return "block assignment to variable: " + varName; 157 } 158 159 boolean isIgnorable() { 160 return false; 161 } 162 } 163 164 | Popular Tags |