freemarker.core.Environment Java Examples
The following examples show how to use
freemarker.core.Environment.
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: ArticleTagDirective.java From stone with GNU General Public License v3.0 | 6 votes |
@Override public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException { final DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); if (map.containsKey(METHOD_KEY)) { String method = map.get(METHOD_KEY).toString(); switch (method) { case "postsCount": environment.setVariable("postsCount", builder.build().wrap(postService.findPostByStatus(PostStatusEnum.PUBLISHED.getCode(), PostTypeEnum.POST_TYPE_POST.getDesc()).size())); break; case "archives": environment.setVariable("archives", builder.build().wrap(postService.findPostGroupByYearAndMonth())); break; case "archivesLess": environment.setVariable("archivesLess", builder.build().wrap(postService.findPostGroupByYear())); break; case "hotPosts": environment.setVariable("hotPosts", builder.build().wrap(postService.hotPosts())); break; default: break; } } templateDirectiveBody.render(environment.getOut()); }
Example #2
Source File: LogoDirective.java From hermes with Apache License 2.0 | 6 votes |
@SuppressWarnings("rawtypes") @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { Properties properties = propertiesRepository.findByCode("app.logo"); Text text = textService.loadById(properties.getValue()); if(text == null){ Logger.error("logo图标信息为空"); env.getOut().write(""); } String logoBase64Code = text.getText(); if (!Strings.empty(logoBase64Code)) { env.getOut().write(logoBase64Code); }else{ Logger.error("logo图标没有初始化,请到后台配置"); } }
Example #3
Source File: StrDirective.java From onetwo with Apache License 2.0 | 6 votes |
@Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { String insertPrefix = getInsertPrefix(params); List<String> trimPrefixs = getTrimPrefixs(params); List<String> trimSuffixs = getTrimSuffixs(params); StringWriter writer = new StringWriter(); body.render(writer); StringBuilder buffer = new StringBuilder(writer.toString().trim()); if (StringUtils.isBlank(buffer)) { return ; } final String sql = buffer.toString().toLowerCase(); trimPrefixs(buffer, sql, trimPrefixs); trimSuffixs(buffer, sql, trimSuffixs); buffer.insert(0, " "); buffer.insert(0, insertPrefix); env.getOut().append(buffer); }
Example #4
Source File: ContextFtlUtil.java From scipio-erp with Apache License 2.0 | 6 votes |
/** * Method providing support for a stack structure having request scope, with fallback to globals. * <p> * <strong>Do not access underlying structure directly.</strong> * * @see #setRequestVar */ static void pushRequestStack(String name, Object value, boolean setLast, HttpServletRequest request, Map<String, Object> context, Environment env) throws TemplateModelException { // NOTE: There is no value wrapping or unwrapping in these methods anymore; we just store them and all wrapping/unwrapping // is left to caller unless absolutely necessary (and in those cases, he specifies the objectWrapper for behavior). //if (value instanceof TemplateModel) { // value = FtlTransformUtil.unwrapPermissive((TemplateModel) value); //} // if env.setGlobalVariable: if (request != null) { updateStack(getRequestVarMapFromReqAttribs(request), name, value, setLast, "request attributes"); } else { Map<String, Object> globalContext = getGlobalContext(context, env); if (globalContext != null) { updateStack(getRequestVarMapFromGlobalContext(globalContext), name, value, setLast, "globalContext"); } else if (env != null) { updateStack(getRequestVarMapFromFtlGlobals(env), name, value, setLast, "FTL globals"); } else { throw new IllegalArgumentException("No request, context or ftl environment to push request scope stack (name: " + name + ")"); } } }
Example #5
Source File: RunServiceMethod.java From scipio-erp with Apache License 2.0 | 6 votes |
private static Map<String, Object> handleException(Exception e, String exMode, Environment env) throws TemplateModelException { int dashIndex = exMode.indexOf('-'); if (dashIndex > 0) { exMode = exMode.substring(0, dashIndex); } if ("null".equals(exMode)) { return null; } else if ("empty".equals(exMode)) { return new HashMap<>(); // Use new map, just in case (not performance-sensitive): Collections.emptyMap(); } else if ("throw".equals(exMode)) { throw new TemplateModelException(e); } else { Map<String, Object> result = "error".equals(exMode) ? ServiceUtil.returnError(e.getMessage()) : new HashMap<>(); result.put("errorEx", e); result.put("errorMessageEx", e.getMessage()); return result; } }
Example #6
Source File: TemplateSource.java From scipio-erp with Apache License 2.0 | 6 votes |
/** * Tries to get appropriate location-based UtilCache in use for templates being rendered. * <p> * FIXME: WARNING: massive limitations here, we do not have access to all the Configuration instances * we'd need to test to implement this, and a host of problems... * as a result I am creating a new two-layer cache system that first keys on the Configuration instances. */ public static UtilCache<String, Template> getTemplateLocationCacheForConfig(Configuration config, Environment env) throws TemplateModelException { Map<Configuration, UtilCache<String, Template>> configTmplLocCaches = TemplateSource.configTmplLocCaches; UtilCache<String, Template> cache = configTmplLocCaches.get(config); if (cache == null) { // double-locking idiom, with configTmplLocCaches as unmodifiable synchronized(TemplateSource.class) { configTmplLocCaches = TemplateSource.configTmplLocCaches; cache = configTmplLocCaches.get(config); if (cache == null) { Map<Configuration, UtilCache<String, Template>> newConfigCacheMap = new HashMap<>(configTmplLocCaches); cache = UtilCache.createUtilCache("templatesource.ftl.location." + (configTmplLocCaches.size() + 1), 0, configTmplCacheExpireTime, false); newConfigCacheMap.put(config, cache); TemplateSource.configTmplLocCaches = newConfigCacheMap; } } } return cache; }
Example #7
Source File: WrapTag.java From javalite with Apache License 2.0 | 6 votes |
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { if(!params.containsKey("with")) { throw new RuntimeException("\"with\" param was not provided"); } String withArgument = params.get("with").toString(); StringWriter innerContent = new StringWriter(); body.render(innerContent); SimpleHash envValues = getHash(env); envValues.putAll(params); envValues.put("page_content", innerContent.toString()); for(Object key : params.keySet()) { if(key.toString().equals("with")) { continue; } else { envValues.put(key.toString(), params.get(key)); } } String path = getTemplatePath(env.getTemplate().getName(), withArgument); Template template = env.getConfiguration().getTemplate(path + ".ftl"); template.process(envValues, env.getOut()); }
Example #8
Source File: NewestAnswerinfo.java From FlyCms with MIT License | 6 votes |
@SuppressWarnings("rawtypes") public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); // 获取页面的参数 Long questionId = null; @SuppressWarnings("unchecked") Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params); for(String str:paramWrap.keySet()){ if("questionId".equals(str)){ questionId = Long.parseLong(paramWrap.get(str).toString()); } } // 获取文件的分页 Answer answer = answerService.findNewestAnswerById(questionId); env.setVariable("answer", builder.build().wrap(answer)); body.render(env.getOut()); }
Example #9
Source File: BaseTag.java From OneBlog with GNU General Public License v3.0 | 6 votes |
@Override public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException { this.verifyParameters(map); String funName = getMethod(map); Method method = null; Class clazz = classBucket.get(clazzPath); try { if (clazz != null && (method = clazz.getDeclaredMethod(funName, Map.class)) != null) { // 核心处理,调用子类的具体方法,获取返回值 Object res = method.invoke(this, map); environment.setVariable(funName, getModel(res)); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { log.error("无法获取[{}]的方法,或者调用[{}]方法发生异常", clazzPath, method, e); } templateDirectiveBody.render(environment.getOut()); }
Example #10
Source File: FreeMarkerWorker.java From scipio-erp with Apache License 2.0 | 6 votes |
protected void handleTemplateExceptionDebug(TemplateException te, Environment env, Writer out) throws TemplateException { StringWriter tempWriter = new StringWriter(); PrintWriter pw = new PrintWriter(tempWriter, true); te.printStackTrace(pw); String stackTrace = tempWriter.toString(); UtilCodec.SimpleEncoder simpleEncoder = FreeMarkerWorker.getWrappedObject("simpleEncoder", env); if (simpleEncoder != null) { stackTrace = simpleEncoder.encode(stackTrace); } try { out.write(stackTrace); } catch (IOException e) { Debug.logError(e, module); } }
Example #11
Source File: SuperDirective.java From metadata with Apache License 2.0 | 6 votes |
@Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { TemplateDirectiveBodyOverrideWraper current = (TemplateDirectiveBodyOverrideWraper) env.getVariable(DirectiveUtils.OVERRIDE_CURRENT_NODE); if (current == null) { throw new TemplateException("<@super/> direction must be child of override", env); } TemplateDirectiveBody parent = current.parentBody; if (parent == null) { throw new TemplateException("not found parent for <@super/>", env); } parent.render(env.getOut()); }
Example #12
Source File: ObjectWrapperUtil.java From scipio-erp with Apache License 2.0 | 6 votes |
@Override public ObjectWrapper getWrapper(Environment env) { ObjectWrapper curr = env.getObjectWrapper(); if (curr instanceof ScipioExtendedObjectWrapper) { if (curr instanceof ScipioBeansWrapper) { if (((BeansWrapper) curr).isSimpleMapWrapper()) { return FreeMarkerWorker.getDefaultOfbizSimpleMapWrapper(); } else { return FreeMarkerWorker.getDefaultOfbizWrapper(); } } else { return FreeMarkerWorker.getDefaultOfbizSimpleMapWrapper(); } } else { return curr; } }
Example #13
Source File: DefineDirective.java From onetwo with Apache License 2.0 | 5 votes |
@Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { String name = DirectivesUtils.getRequiredParameterByString(params, PARAMS_NAME); OverrideBodyWraper override = DirectivesUtils.getOverrideBody(env, name); if(override!=null){ if(override.render) return ; override.render(env.getOut()); }else{ if(body!=null) body.render(env.getOut()); } }
Example #14
Source File: AuthenticatedTag.java From mblog with GNU General Public License v3.0 | 5 votes |
@Override public void render(Environment env, Map params, TemplateDirectiveBody body) throws IOException, TemplateException { if (getSubject() != null && (getSubject().isAuthenticated() || getSubject().isRemembered())) { if (log.isDebugEnabled()) { log.debug("Subject exists and is authenticated. Tag body will be evaluated."); } renderBody(env, body); } else { if (log.isDebugEnabled()) { log.debug("Subject does not exist or is not authenticated. Tag body will not be evaluated."); } } }
Example #15
Source File: CmsPageUrlDirective.java From scipio-erp with Apache License 2.0 | 5 votes |
public static boolean handleError(Environment env, Throwable t, String errorMsg) throws CmsException, TemplateException { // DEV NOTE: you could theoretically do something like this, but it just makes things worse and inconsistent with scipio macros // if (CmsRenderUtil.getDirectiveRenderExceptionMode(env, urlLiveExceptionMode) == RenderExceptionMode.BLANK) { // try { // env.getOut().write("#"); // } catch(Exception e) { // Debug.logError(e, module); // } // } return CmsRenderUtil.handleDirectiveError(env, "Page link failed", t, errorMsg, urlLiveExceptionMode, module); }
Example #16
Source File: PrincipalTag.java From SpringBoot-Base-System with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void render(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateDirectiveBody body) throws IOException, TemplateException { String result = null; if (getSubject() != null) { // Get the principal to print out Object principal; if (getType(params) == null) { principal = getSubject().getPrincipal(); } else { principal = getPrincipalFromClassName(params); } // Get the string value of the principal if (principal != null) { String property = getProperty(params); if (property == null) { result = principal.toString(); } else { result = getPrincipalProperty(principal, property); } } } // Print out the principal value if not null if (result != null) { try { env.getOut().write(result); } catch (IOException ex) { throw new TemplateException("Error writing [" + result + "] to Freemarker.", ex, env); } } }
Example #17
Source File: ContextFtlUtil.java From scipio-erp with Apache License 2.0 | 5 votes |
private static Map<String, Object> getRequestVarMapFromFtlGlobals(Environment env) { RequestVarMapWrapperModel mapWrapper = null; try { mapWrapper = (RequestVarMapWrapperModel) env.getGlobalVariable(ContextFtlUtil.REQUEST_VAR_MAP_NAME_FTLGLOBALS); } catch (TemplateModelException e) { Debug.logError(e, "Scipio: Error getting request var map from FTL globals", module); } if (mapWrapper == null) { // FIXME: should try to get underlying map from request or globalContext mapWrapper = new RequestVarMapWrapperModel(); env.setGlobalVariable(ContextFtlUtil.REQUEST_VAR_MAP_NAME_FTLGLOBALS, mapWrapper); } return mapWrapper.getRawMap(); }
Example #18
Source File: LangFtlUtil.java From scipio-erp with Apache License 2.0 | 5 votes |
/** * Checks if the current env wrapper is a special escaping wrapper, and if so, * returns a non-escaping one. */ public static ObjectWrapper getNonEscapingObjectWrapper(Environment env) { ObjectWrapper objectWrapper = env.getObjectWrapper(); if (objectWrapper instanceof ScipioExtendedObjectWrapper) { return FreeMarkerWorker.getDefaultOfbizWrapper(); } else { return objectWrapper; } }
Example #19
Source File: PrincipalTag.java From mblog with GNU General Public License v3.0 | 5 votes |
@SuppressWarnings("unchecked") @Override public void render(Environment env, Map params, TemplateDirectiveBody body) throws IOException, TemplateException { String result = null; if (getSubject() != null) { // Get the principal to print out Object principal; if (getType(params) == null) { principal = getSubject().getPrincipal(); } else { principal = getPrincipalFromClassName(params); } // Get the string value of the principal if (principal != null) { String property = getProperty(params); if (property == null) { result = principal.toString(); } else { result = getPrincipalProperty(principal, property); } } } // Print out the principal value if not null if (result != null) { try { env.getOut().write(result); } catch (IOException ex) { throw new TemplateException("Error writing [" + result + "] to Freemarker.", ex, env); } } }
Example #20
Source File: TagsDirective.java From pybbs with GNU Affero General Public License v3.0 | 5 votes |
@Override public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException { Integer pageNo = Integer.parseInt(map.get("pageNo").toString()); Integer pageSize = Integer.parseInt(map.get("pageSize").toString()); IPage<Tag> page = tagService.selectAll(pageNo, pageSize, null); DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_28); environment.setVariable("page", builder.build().wrap(page)); templateDirectiveBody.render(environment.getOut()); }
Example #21
Source File: MultiVarMethod.java From scipio-erp with Apache License 2.0 | 5 votes |
@Override protected Object execTyped(List<TemplateModel> args) throws TemplateModelException { TemplateHashModelEx varMapsModel = (TemplateHashModelEx) args.get(0); CommonVarMaps<Map<String, Object>> varMaps = CommonVarMaps.getRawMaps(varMapsModel); Environment env = FreeMarkerWorker.getCurrentEnvironment(); setVars(varMaps, env); return new SimpleScalar(""); }
Example #22
Source File: Feedpage.java From FlyCms with MIT License | 5 votes |
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); // 获取页面的参数 //所属主信息类型,0是所有,1是文章,2是小组话题 Long userId=null; Integer status=2; //翻页页数 Integer p = 1; //每页记录条数 Integer rows = 10; //处理标签变量 Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params); for(String str:paramWrap.keySet()){ if("userId".equals(str)){ userId = Long.parseLong(paramWrap.get(str).toString()); } if("status".equals(str)){ status = Integer.parseInt(paramWrap.get(str).toString()); } if("p".equals(str)){ p = Integer.parseInt(paramWrap.get(str).toString()); } if("rows".equals(str)){ rows = Integer.parseInt(paramWrap.get(str).toString()); } } // 获取文件的分页 try { PageVo<Feed> pageVo = feedService.getUserListFeedPage(userId,status,p,rows); env.setVariable("feed_page", builder.build().wrap(pageVo)); } catch (Exception e) { env.setVariable("feed_page", builder.build().wrap(null)); } body.render(env.getOut()); }
Example #23
Source File: NotAuthenticatedTag.java From mblog with GNU General Public License v3.0 | 5 votes |
@Override public void render(Environment env, Map params, TemplateDirectiveBody body) throws IOException, TemplateException { if (getSubject() == null || !(getSubject().isAuthenticated() || getSubject().isRemembered())) { log.debug("Subject does not exist or is not authenticated. Tag body will be evaluated."); renderBody(env, body); } else { log.debug("Subject exists and is authenticated. Tag body will not be evaluated."); } }
Example #24
Source File: ExtendsDirective.java From metadata with Apache License 2.0 | 5 votes |
@Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { String name = DirectiveUtils.getRequiredParam(params, "name"); String encoding = DirectiveUtils.getParam(params, "encoding",null); String includeTemplateName = TemplateCache.getFullTemplatePath(env, getTemplatePath(env), name); env.include(includeTemplateName, encoding, true); }
Example #25
Source File: BrowserTagDirective.java From MaxKey with Apache License 2.0 | 5 votes |
@Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { String browser = params.get("name").toString(); String userAgent = request.getHeader("User-Agent"); env.getOut().append("<!--<div style='display:none'>"+userAgent+"</div>-->"); if(userAgent.indexOf(browser)>0){ body.render(env.getOut()); } }
Example #26
Source File: ExecuteControllerDirective.java From engine with GNU General Public License v3.0 | 5 votes |
protected String getPath(TemplateModel pathParam, Environment env) throws TemplateException { Object unwrappedPath = DeepUnwrap.unwrap(pathParam); if (unwrappedPath instanceof String) { return (String)unwrappedPath; } else { throw new TemplateException("Param '" + PATH_PARAM_NAME + " of unexpected type: expected: " + String.class.getName() + ", actual: " + unwrappedPath.getClass().getName(), env); } }
Example #27
Source File: LangFtlUtil.java From scipio-erp with Apache License 2.0 | 5 votes |
/** * 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 #28
Source File: ContextFtlUtil.java From scipio-erp with Apache License 2.0 | 5 votes |
public static Object readRequestStack(String name, Environment env) throws TemplateModelException { HttpServletRequest request = getRequest(env); Map<String, Object> context = null; if (request == null) { context = getContext(env); } return ContextFtlUtil.readRequestStack(name, false, request, context, env); }
Example #29
Source File: ObjectWrapperUtil.java From scipio-erp with Apache License 2.0 | 5 votes |
@Override public ObjectWrapper getWrapper(Environment env) { ObjectWrapper wrapper = env.getObjectWrapper(); // FIXME: Support for extended ScipioDefaultObjectWrapper: it is currently ditched by this code if (wrapper instanceof ScipioExtendedBeansWrapper && ((BeansWrapper) wrapper).isSimpleMapWrapper() == simpleMap) { return wrapper; } else { // semi-reliable way to get the language Object simpleEncoder = null; try { simpleEncoder = LangFtlUtil.unwrapOrNull(env.getGlobalVariable("simpleEncoder")); } catch (TemplateModelException e) { ; } if (simpleEncoder != null) { if (simpleEncoder instanceof UtilCodec.HtmlEncoder) { // heuristic return simpleMap ? defaultHtmlExtendedWrapper : defaultHtmlExtendedSimpleMapWrapper; } else { // TODO: REVIEW: what is this doing for non-html?? HtmlWidget was missing other lang support, // that's why not doing it here... return simpleMap ? FreeMarkerWorker.getDefaultOfbizWrapper() : FreeMarkerWorker.getDefaultOfbizSimpleMapWrapper(); } } else { // FIXME: if we don't know the lang, we have to play it safe and use html return simpleMap ? defaultHtmlExtendedWrapper : defaultHtmlExtendedSimpleMapWrapper; } } }
Example #30
Source File: MessagesDirective.java From hermes with Apache License 2.0 | 5 votes |
@SuppressWarnings("rawtypes") @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { if (!params.containsKey(PARAM_NAME_KEY)) { throw new TemplateModelException("key is necessary!"); } env.getOut().write(App.message(params.get(PARAM_NAME_KEY).toString())); }