Java Code Examples for freemarker.core.Environment#getVariable()

The following examples show how to use freemarker.core.Environment#getVariable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DirectiveUtils.java    From Lottery with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 将params的值复制到variable中
 * 
 * @param env
 * @param params
 * @return 原Variable中的值
 * @throws TemplateException
 */
public static Map<String, TemplateModel> addParamsToVariable(
		Environment env, Map<String, TemplateModel> params)
		throws TemplateException {
	Map<String, TemplateModel> origMap = new HashMap<String, TemplateModel>();
	if (params.size() <= 0) {
		return origMap;
	}
	Set<Map.Entry<String, TemplateModel>> entrySet = params.entrySet();
	String key;
	TemplateModel value;
	for (Map.Entry<String, TemplateModel> entry : entrySet) {
		key = entry.getKey();
		value = env.getVariable(key);
		if (value != null) {
			origMap.put(key, value);
		}
		env.setVariable(key, entry.getValue());
	}
	return origMap;
}
 
Example 2
Source File: FreeMarkerWorker.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
* Gets BeanModel from FreeMarker context and returns the object that it wraps.
* @param varName the name of the variable in the FreeMarker context.
* @param env the FreeMarker Environment
*/
public static <T> T getWrappedObject(String varName, Environment env) {
    Object obj = null;
    try {
        obj = env.getVariable(varName);
        if (obj != null) {
            if (obj == TemplateModel.NOTHING) {
                obj = null;
            } else if (obj instanceof BeanModel) {
                BeanModel bean = (BeanModel) obj;
                obj = bean.getWrappedObject();
            } else if (obj instanceof SimpleScalar) {
                obj = obj.toString();
            }
        }
    } catch (TemplateModelException e) {
        Debug.logInfo(e.getMessage(), module);
    }
    return UtilGenerics.<T>cast(obj);
}
 
Example 3
Source File: BlockDirective.java    From freemarker-template-inheritance with Apache License 2.0 5 votes vote down vote up
private String getPutContents(Environment env, String blockName) throws TemplateModelException {
    SimpleScalar putContentsModel = (SimpleScalar) env.getVariable(getBlockContentsVarName(blockName));
    String putContents = "";
    if (putContentsModel != null) {
        putContents = putContentsModel.getAsString();
    }
    return putContents;
}
 
Example 4
Source File: ExecuteControllerDirective.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
protected SiteItem getContentModel(Environment env) throws TemplateException {
    TemplateModel contentModel = env.getVariable(CrafterPageView.KEY_CONTENT_MODEL);
    if (contentModel != null) {
        Object unwrappedContentModel = DeepUnwrap.unwrap(contentModel);
        if (unwrappedContentModel instanceof SiteItem) {
            return (SiteItem)unwrappedContentModel;
        } else {
            throw new TemplateException("Variable '" + CrafterPageView.KEY_CONTENT_MODEL + " of unexpected type: expected: " +
                                        SiteItem.class.getName() + ", actual: " + unwrappedContentModel.getClass().getName(),
                                        env);
        }
    } else {
        return null;
    }
}
 
Example 5
Source File: HeadInfoTag.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String extractAttribute() throws JspException {
if (null == this.getVar()) {
	return null;
}
String objectToString = null;
try {
	Object object = this.pageContext.getAttribute(this.getVar());
	if (null == object) {
		Environment environment = Environment.getCurrentEnvironment();
		if (null != environment) {
			Object wrapper = environment.getVariable(this.getVar());
			if (null != wrapper) {
				if (wrapper instanceof StringModel) {
					object = ((StringModel) wrapper).getWrappedObject();
				} else {
					object = wrapper;
				}
			}
		}
	}
	if (null != object) {
		objectToString = object.toString();
	}
      } catch (Throwable t) {
      	_logger.error("error extracting freemarker attribute", t);
          throw new JspException("Error extracting freemarker attribute", t);
      }
return objectToString;
  }
 
Example 6
Source File: FreemarkerTemplateParameterTag.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
  public int doStartTag() throws JspException {
ServletRequest request = this.pageContext.getRequest();
RequestContext reqCtx = (RequestContext) request.getAttribute(RequestContext.REQCTX);
try {
	ExecutorBeanContainer ebc = (ExecutorBeanContainer) reqCtx.getExtraParam(SystemConstants.EXTRAPAR_EXECUTOR_BEAN_CONTAINER);
	TemplateModel templateModel = ebc.getTemplateModel();
	if (!(templateModel instanceof AllHttpScopesHashModel)) {
		return EVAL_BODY_INCLUDE;
	}
	AllHttpScopesHashModel hashModel = (AllHttpScopesHashModel) templateModel;
	Object object = this.pageContext.getAttribute(this.getValueName());
	if (null == object) {
		Environment environment = Environment.getCurrentEnvironment();
		if (null != environment) {
			Object wrapper = environment.getVariable(this.getValueName());
			if (null != wrapper) {
				if (wrapper instanceof StringModel) {
					object = ((StringModel) wrapper).getWrappedObject();
				} else {
					object = wrapper;
				}
			}
		}
	}
	if (null != object) {
		hashModel.put(this.getVar(), object);
	}
      } catch (Throwable t) {
      	_logger.error("error in doStartTag", t);
          throw new JspException("Error during tag initialization", t);
      }
      return EVAL_BODY_INCLUDE;
  }
 
Example 7
Source File: AbstractDirective.java    From onetwo with Apache License 2.0 5 votes vote down vote up
protected <T> T getVariable(String varName, Environment env) throws TemplateModelException{
	Object value = env.getVariable(varName);
	if (value instanceof BeanModel) {
		value = ((BeanModel) value).getWrappedObject();
	}
	return (T)value;
}
 
Example 8
Source File: FtlUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static TemplateModel getVariable(Environment env, String name, boolean throwIfError){
	TemplateModel model = null;
	try {
		model = env.getVariable(name);
	} catch (Exception e) {
		if(throwIfError)
			throw new BaseException("get variable["+name+"] error: " + e.getMessage(), e);
	}
	return model;
}
 
Example 9
Source File: LangFtlUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Executes an arbitrary FTL function - non-abstracted version (for optimization only!).
 */
public static TemplateModel execFunction(Template functionCall, TemplateModel[] args, Environment env) throws TemplateModelException {
    final int argCount = (args != null) ? args.length : 0;
    for(int i=0; i < argCount; i++) {
        env.setVariable("_scpEfnArg"+i, args[i]);
    }
    execFtlCode(functionCall, env);
    return env.getVariable("_scpEfnRes");
}
 
Example 10
Source File: LangFtlUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Executes an arbitrary FTL built-in - non-abstracted version (for optimization only!).
 */
public static TemplateModel execBuiltIn(Template builtInCall, TemplateModel value, TemplateModel[] builtInArgs, Environment env) throws TemplateModelException {
    final int argCount = (builtInArgs != null) ? builtInArgs.length : 0;
    env.setVariable("_scpEbiVal", value);
    for(int i=0; i < argCount; i++) {
        env.setVariable("_scpEbiArg"+i, builtInArgs[i]);
    }
    execFtlCode(builtInCall, env);
    return env.getVariable("_scpEbiRes");
}
 
Example 11
Source File: SetGlobalContextFieldMethod.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@Override
public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException {
    if (args == null || args.size() != 2)
        throw new TemplateModelException("Invalid number of arguments");
    if (!(args.get(0) instanceof TemplateScalarModel))
        throw new TemplateModelException("First argument not an instance of TemplateScalarModel");
    // SCIPIO: This is too limiting
    //if (!(args.get(1) instanceof BeanModel) && !(args.get(1) instanceof TemplateNumberModel) && !(args.get(1) instanceof TemplateScalarModel))
    //    throw new TemplateModelException("Second argument not an instance of BeanModel nor TemplateNumberModel nor TemplateScalarModel");

    Environment env = FreeMarkerWorker.getCurrentEnvironment();
    BeanModel globalContextModel = (BeanModel) env.getVariable("globalContext");
    @SuppressWarnings("unchecked")
    Map<String, Object> globalContext = (Map<String, Object>) globalContextModel.getWrappedObject();

    String name = LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(0)));
    Object valueModel = args.get(1);
    Object value = null;
    // SCIPIO: Let DeepUnwrap handle this...
    //if (args.get(1) instanceof TemplateScalarModel)
    //    value = ((TemplateScalarModel) args.get(1)).getAsString();
    //if (args.get(1) instanceof TemplateNumberModel)
    //    value = ((TemplateNumberModel) args.get(1)).getAsNumber();
    //if (args.get(1) instanceof BeanModel)
    //    value = ((BeanModel) args.get(1)).getWrappedObject();
    // SCIPIO: NOTE: Unlike this above, this call will avoid the auto-escaping as implemented by Ofbiz (sensitive to DeepUnwrap implementation)
    value = LangFtlUtil.unwrapAlwaysUnlessNull(valueModel);

    globalContext.put(name, value);
    return new SimpleScalar("");
}
 
Example 12
Source File: SetContextFieldTransform.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException {
    if (args == null || args.size() != 2)
        throw new TemplateModelException("Invalid number of arguements");
    if (!(args.get(0) instanceof TemplateScalarModel))
        throw new TemplateModelException("First argument not an instance of TemplateScalarModel");
    // SCIPIO: This is too limiting...
    //if (!(args.get(1) instanceof BeanModel) && !(args.get(1) instanceof TemplateNumberModel) && !(args.get(1) instanceof TemplateScalarModel))
    //    throw new TemplateModelException("Second argument not an instance of BeanModel nor TemplateNumberModel nor TemplateScalarModel");

    Environment env = FreeMarkerWorker.getCurrentEnvironment();
    BeanModel req = (BeanModel)env.getVariable("context");
    Map<String, Object> context = (Map<String, Object>) req.getWrappedObject();

    // SCIPIO: name should not be escaped
    //String name = ((TemplateScalarModel) args.get(0)).getAsString();
    String name = LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(0)));
    Object valueModel = args.get(1);
    Object value = null;
    // SCIPIO: Let DeepUnwrap handle this...
    //if (args.get(1) instanceof TemplateNumberModel)
    //    value = ((TemplateNumberModel) args.get(1)).getAsNumber();
    //if (args.get(1) instanceof BeanModel)
    //    value = ((BeanModel) args.get(1)).getWrappedObject();
    // SCIPIO: NOTE: Unlike this above, this call will avoid the auto-escaping as implemented by Ofbiz (sensitive to DeepUnwrap implementation)
    value = LangFtlUtil.unwrapAlwaysUnlessNull(valueModel);

    context.put(name, value);
    return new SimpleScalar("");
}
 
Example 13
Source File: SetRequestAttributeMethod.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException {
    if (args == null || args.size() != 2)
        throw new TemplateModelException("Invalid number of arguements");
    if (!(args.get(0) instanceof TemplateScalarModel))
        throw new TemplateModelException("First argument not an instance of TemplateScalarModel");
    // SCIPIO: This is too limiting...
    //if (!(args.get(1) instanceof BeanModel) && !(args.get(1) instanceof TemplateNumberModel) && !(args.get(1) instanceof TemplateScalarModel))
    //    throw new TemplateModelException("Second argument not an instance of BeanModel nor TemplateNumberModel nor TemplateScalarModel");

    Environment env = FreeMarkerWorker.getCurrentEnvironment();
    BeanModel req = (BeanModel)env.getVariable("request");
    HttpServletRequest request = (HttpServletRequest) req.getWrappedObject();

    // SCIPIO: name should not be escaped
    //String name = ((TemplateScalarModel) args.get(0)).getAsString();
    String name = LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(0)));
    Object valueModel = args.get(1);
    Object value = null;
    // SCIPIO: Let DeepUnwrap handle this...
    //if (args.get(1) instanceof TemplateScalarModel)
    //    value = ((TemplateScalarModel) args.get(1)).getAsString();
    //if (args.get(1) instanceof TemplateNumberModel)
    //    value = ((TemplateNumberModel) args.get(1)).getAsNumber();
    //if (args.get(1) instanceof BeanModel)
    //    value = ((BeanModel) args.get(1)).getWrappedObject();
    // SCIPIO: NOTE: Unlike this above, this call will avoid the auto-escaping as implemented by Ofbiz (sensitive to DeepUnwrap implementation)
    value = LangFtlUtil.unwrapAlwaysUnlessNull(valueModel);

    request.setAttribute(name, value);
    return new SimpleScalar("");
}
 
Example 14
Source File: CmsRenderUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Map<String, Object> getRenderContextGeneric(Environment env) throws TemplateModelException {
    TemplateModel pcm = env.getVariable("context");
    if (pcm != null && pcm instanceof WrapperTemplateModel) {
        Object obj = ((WrapperTemplateModel) pcm).getWrappedObject();
        if (obj instanceof MapStack) {
            return (Map<String, Object>) obj;
        }
    }
    return null;
}
 
Example 15
Source File: CmsRenderUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static MapStack<String> getRenderContext(Environment env) throws TemplateModelException {
    TemplateModel pcm = env.getVariable("context");
    if (pcm != null && pcm instanceof WrapperTemplateModel) {
        Object obj = ((WrapperTemplateModel) pcm).getWrappedObject();
        if (obj instanceof MapStack) {
            return (MapStack<String>) obj;
        }
    }
    return null;
}
 
Example 16
Source File: BlockDirective.java    From freemarker-template-inheritance with Apache License 2.0 5 votes vote down vote up
private PutType getPutType(Environment env, String blockName) throws TemplateException {
    SimpleScalar putTypeScalar = (SimpleScalar) env.getVariable(getBlockTypeVarName(blockName));
    if (putTypeScalar == null) {
        return PutType.APPEND;
    }

    return PutType.valueOf(putTypeScalar.getAsString());
}
 
Example 17
Source File: ContextFtlUtil.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static HttpServletResponse getResponse(Environment env) throws TemplateModelException {
    WrapperTemplateModel req = (WrapperTemplateModel) env.getVariable("response");
    return (req != null) ? (HttpServletResponse) req.getWrappedObject() : null;
}
 
Example 18
Source File: ContextFtlUtil.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static HttpServletRequest getRequest(Environment env) throws TemplateModelException {
    WrapperTemplateModel req = (WrapperTemplateModel) env.getVariable("request");
    return (req != null) ? (HttpServletRequest) req.getWrappedObject() : null;
}
 
Example 19
Source File: PassthroughFixDirective.java    From helidon-build-tools with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(Environment env,
        Map params, TemplateModel[] loopVars,
        TemplateDirectiveBody body)
        throws TemplateException, IOException {

    if (loopVars.length != 0) {
            throw new TemplateModelException(
                "This directive does not allow loop variables.");
    }

    // Check if no parameters were given:
    if (body != null) {
        throw new TemplateModelException(
                "This directive does not allow body content.");
    }

    TemplateModel textVar = env.getVariable("text");
    if (!(textVar instanceof TemplateScalarModel)) {
        throw new TemplateModelException(
                "text variable is not a TemplateScalarModel");
    }

    String text = ((TemplateScalarModel) textVar).getAsString();

    if (PLACEHOLDER.equals(text)) {

        TemplateModel parentVar = env.getVariable("parent");
        if (!(parentVar instanceof ContentNodeHashModel)) {
            throw new TemplateModelException(
                    "pareant variable is not a ContentNodeHashModel");
        }

        ContentNode parent = ((ContentNodeHashModel) parentVar).getContentNode();

        String source;
        if (parent instanceof Block) {
            source = ((Block) parent).getSource();
        } else if (parent instanceof Cell) {
            source = ((Cell) parent).getSource();
        } else {
            throw new TemplateModelException(
                    "parent is not a Block or a Cell");
        }

        if (source == null || source.isEmpty()) {
            throw new TemplateModelException(
                    "source is null or empty");
        }

        String fixed = formatInlineSource(source);
        env.getOut().write(fixed);

    } else {
        // nothing to do, just write the text out
        env.getOut().write(text);
    }
}
 
Example 20
Source File: FreeMarkerInlineRenderUtils.java    From rice with Educational Community License v2.0 3 votes vote down vote up
/**
 * Resovle a FreeMarker variable as a FreeMarker template model object.
 *
 * @param env The FreeMarker environment.
 * @param name The name of the variable.
 * @return The FreeMarker variable, resolved as a FreeMarker template model object.
 * @see #resolve(Environment, String, Class) for the preferred means to resolve variables for
 * inline rendering.
 */
public static TemplateModel resolveModel(Environment env, String name) {
    try {
        return env.getVariable(name);
    } catch (TemplateModelException e) {
        throw new IllegalArgumentException("Failed to resolve " + name + " in current freemarker environment", e);
    }
}