Java Code Examples for freemarker.template.TemplateDirectiveBody#render()

The following examples show how to use freemarker.template.TemplateDirectiveBody#render() . 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: AbstractDirective.java    From onetwo with Apache License 2.0 6 votes vote down vote up
protected String getBodyContent(TemplateDirectiveBody body){
		StringWriter sw = null;
		String bodyContent = "";
		try {
//			body.render(env.getOut());
			if(body!=null){
				sw = new StringWriter();
				body.render(sw);
				bodyContent = sw.toString();
			}
		} catch (Exception e) {
			LangUtils.throwBaseException("render error : " + e.getMessage(), e);
//			e.printStackTrace();
		} finally{
			LangUtils.closeIO(sw);
		}
		return bodyContent;
	}
 
Example 2
Source File: SuperDirective.java    From metadata with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: DateRangeDirective.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		TemplateModel from = FtlUtils.getRequiredParameter(params, PARAMS_FROM);
		TemplateModel to = FtlUtils.getRequiredParameter(params, PARAMS_TO);
		String joiner = FtlUtils.getParameterByString(params, PARAMS_JOINER, "");
		String type = FtlUtils.getParameterByString(params, PARAMS_TYPE, DateType.date.toString());
//		String format = FtlUtils.getParameterByString(params, PARAMS_FORMAT, DateUtil.Date_Only);
		boolean includeEnd = FtlUtils.getParameterByBoolean(params, PARAMS_INCLUDE_END, false);

		List<?> listDatas = null;
		DateType datetype = DateType.valueOf(type);
		String fromStr = from.toString();
		String toStr = to.toString();
		DateInterval interval = DateInterval.in(fromStr, toStr);
		listDatas = interval.getInterval(datetype, 1, includeEnd);
		
		int index = 0;
		for(Object data : listDatas){
			if(loopVars.length>=1)
				loopVars[0] = FtlUtils.wrapAsModel(data);
			if(loopVars.length>=2)
				loopVars[1] = FtlUtils.wrapAsModel(index);
			
			if(index!=0)
				env.getOut().write(joiner);
			
			body.render(env.getOut());
			index++;
		}
	}
 
Example 4
Source File: FtlUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static void render(String tag, Environment env, TemplateDirectiveBody body){
	if(body==null || env==null)
		return ;
	try {
		body.render(env.getOut());
	} catch (Exception e) {
		LangUtils.throwBaseException("render tempalte["+tag+"] error : "+e.getMessage(), e);
	} 
}
 
Example 5
Source File: NavsTags.java    From cms with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {
    if (params.get("id") == null)
        return;
    String id = params.get("id").toString();

    List<Navs> navs = SystemCacheManager.get(ConstantsUtils.TE_NAVS_KEY + id, List.class);

    if (navs == null) {
        Category model = new Category();
        model.setShowModes("1");
        model.setSiteId(Long.parseLong(id));
        List<Category> categorys = categoryService.getList(model);
        navs = getRootNodes(categorys);

        for (Navs nav : navs) {
            childNodes(categorys, nav);
        }
        SystemCacheManager.put(ConstantsUtils.TE_NAVS_KEY + id, navs);
    }

    env.setVariable("navs", wrap(navs));
    if (body != null) {
        body.render(env.getOut());
    }
}
 
Example 6
Source File: BrowserTagDirective.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@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 7
Source File: AdTags.java    From cms with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    SimpleScalar id = (SimpleScalar) params.get("id");
    List<Ad> ads = adService.getAdByPositionId(Long.parseLong(id.toString()));

    env.setVariable("ads", wrap(ads));
    if (body != null) {
        body.render(env.getOut());
    }
}
 
Example 8
Source File: VirtualSectionDirective.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
protected void executeTyped(Environment env, Map<String, TemplateModel> params, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {
    Writer writer = env.getOut();

    // NOTE: this can only work if we already had a RenderWriter.
    // if not, don't even bother trying.
    if (writer instanceof RenderWriter) {
        Map<String, Object> context = ContextFtlUtil.getContext(env);
        WidgetRenderTargetState renderTargetState = WidgetRenderTargetExpr.getRenderTargetState(context);
        if (renderTargetState.isEnabled()) {
            String name = TransformUtil.getStringNonEscapingArg(params, "name");
            String containsExpr = TransformUtil.getStringNonEscapingArg(params, "contains");
            String location = "unknown-location"; // FIXME
            ModelFtlWidget widget = new ModelVirtualSectionFtlWidget(name, location, containsExpr);

            WidgetRenderTargetState.ExecutionInfo execInfo = renderTargetState.handleShouldExecute(widget, writer, context, null);
            if (!execInfo.shouldExecute()) {
                return;
            }
            try {
                if (body != null) {
                    body.render((Writer) execInfo.getWriterForElementRender());
                }
            } finally {
                execInfo.handleFinished(context); // SCIPIO: return logic
            }
            return;
        }
    }

    body.render(writer);
}
 
Example 9
Source File: BlockDirective.java    From metadata with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env,
					Map params, TemplateModel[] loopVars,
					TemplateDirectiveBody body) throws TemplateException, IOException {
	String name = DirectiveUtils.getRequiredParam(params, "name");
	TemplateDirectiveBodyOverrideWraper overrideBody = DirectiveUtils.getOverrideBody(env, name);
	if(overrideBody == null) {
		if(body != null) {
			body.render(env.getOut());
		}
	}else {
		DirectiveUtils.setTopBodyForParentBody(env, new TemplateDirectiveBodyOverrideWraper(body,env), overrideBody);
		overrideBody.render(env.getOut());
	}
}
 
Example 10
Source File: CustomLayoutDirective.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env,
                    Map params,
                    TemplateModel[] loopVars,
                    TemplateDirectiveBody body)
        throws TemplateException, IOException {

    TemplateModel dataModel = env.getDataModel().get("this");
    if (!(dataModel instanceof ContentNodeHashModel)) {
        throw new TemplateModelException(
                "Data model is not a ContentNodeHashModel");
    }
    ContentNode node = ((ContentNodeHashModel) dataModel).getContentNode();
    if (node == null) {
        throw new TemplateModelException("'this' has a null content-node");
    }

    Object page = node.getDocument().getAttribute("page");
    if (page == null || !(page instanceof Page)) {
        throw new TemplateModelException("Unable to get page instance");
    }

    if (body == null) {
        throw new TemplateModelException("Body is null");
    }
    StringWriter writer = new StringWriter();
    body.render(writer);
    mappings.put(((Page) page).getSourcePath(), writer.toString());
}
 
Example 11
Source File: ProfileDirective.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
	if(params.containsKey(PARAMS_ACTIVE)){
		boolean active = DirectivesUtils.getParameterByString(params, PARAMS_ACTIVE, "false").equals("true");
		TimeProfileStack.setActive(active);
	}
	String name = DirectivesUtils.getRequiredParameterByString(params, "name");
	TimeProfileStack.push(name);
	body.render(env.getOut());
	TimeProfileStack.pop(name);
}
 
Example 12
Source File: ForeachDirective.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
	TemplateModel listModel = FtlUtils.getRequiredParameter(params, PARAMS_LIST);
	String joiner = FtlUtils.getParameterByString(params, PARAMS_JOINER, "");
	if(StringUtils.isBlank(joiner))
		joiner = FtlUtils.getParameterByString(params, PARAMS_SEPARATOR, "");//兼容当初定义错的写法
	
	Object datas = null;
	if(listModel instanceof BeanModel){
		datas = ((BeanModel) listModel).getWrappedObject();
	}else{
		throw new BaseException("error: " + listModel);
	}
	
	List<?> listDatas = LangUtils.asList(datas);
	int index = 0;
	for(Object data : listDatas){
		if(loopVars.length>=1)
			loopVars[0] = FtlUtils.wrapAsModel(data);
		if(loopVars.length>=2)
			loopVars[1] = FtlUtils.wrapAsModel(index);
		
		if(index!=0)
			env.getOut().write(joiner);
		
		body.render(env.getOut());
		index++;
	}
}
 
Example 13
Source File: Areaslist.java    From FlyCms with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void execute(Environment env, Map params, TemplateModel[] loopVars,
		TemplateDirectiveBody body) throws TemplateException, IOException {
	DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
	// 获取页面的参数
	//指定父级id
	int parentId = 0;
	
	//处理标签变量
	Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
	for(String str:paramWrap.keySet()){ 
		if("parentId".equals(str)){
			if(!NumberUtils.isNumber(paramWrap.get(str).toString())) {
				parentId=0;
			}else {
				if(!StringHelperUtils.checkInteger(paramWrap.get(str).toString())) {
					parentId=0;
				}else {
					parentId = Integer.parseInt(paramWrap.get(str).toString());
				}
			}
		}
	}
	// 获取文件的分页
	try {
		List<Areas> pageVo = areasService.selectAreasByPid(parentId);
		env.setVariable("areaslist", builder.build().wrap(pageVo));
	} catch (Exception e) {
		env.setVariable("areaslist", builder.build().wrap(null));
	}
	body.render(env.getOut());
}
 
Example 14
Source File: DefineDirective.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@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 15
Source File: ExtendsDirective.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
	String file = DirectivesUtils.getParameterByString(params, PARAMS_FILE, DEFAULT_LAYOUT);
	
	String template = env.toFullTemplateName("/", getActaulFile(params, file));
	if(!template.contains(".")){
		template += FTL;
	}
	body.render(env.getOut());
	env.include(template, DirectivesUtils.ENCODING, true);
}
 
Example 16
Source File: VueBindingsDirective.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env,
                    Map params,
                    TemplateModel[] loopVars,
                    TemplateDirectiveBody body)
        throws TemplateException, IOException {

    TemplateModel dataModel = env.getDataModel().get("this");
    if (!(dataModel instanceof ContentNodeHashModel)) {
        throw new TemplateModelException(
                "Data model is not a ContentNodeHashModel");
    }
    ContentNode node = ((ContentNodeHashModel) dataModel).getContentNode();
    if (node == null) {
        throw new TemplateModelException("'this' has a null content-node");
    }

    Object page = node.getDocument().getAttribute("page");
    if (page == null || !(page instanceof Page)) {
        throw new TemplateModelException("Unable to get page instance");
    }

    if (body == null) {
        throw new TemplateModelException("Body is null");
    }
    StringWriter writer = new StringWriter();
    body.render(writer);
    bindings.put(((Page) page).getSourcePath(), writer.toString());
}
 
Example 17
Source File: SecureTag.java    From SpringBoot-Base-System with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected void renderBody(Environment env, TemplateDirectiveBody body) throws IOException, TemplateException {
    if (body != null) {
        body.render(env.getOut());
    }
}
 
Example 18
Source File: Questionpage.java    From FlyCms with MIT License 4 votes vote down vote up
@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是小组话题
	String title = null;

	Long userId = null;

	String createTime=null;
	
	Integer status=null;
	/**
	 *
	 * § orderby='hot' 或 orderby='click' 表示按点击数排列
	 * § orderby='sortrank' 或 orderby='pubdate' 按出版时间排列
	 * § orderby=='lastpost' 按最后评论时间
	 * § orderby=='scores' 按得分排序
	 * § orderby='id' 按文章ID排序
	 */
	String orderby=null;

	String order=null;

	//翻页页数
	Integer p = 1;
	//每页记录条数
	Integer rows = 10;
	//处理标签变量
	Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
	for(String str:paramWrap.keySet()){ 
		if("title".equals(str)){
			title = paramWrap.get(str).toString();
		}
		if("userId".equals(str)){
			userId = Long.parseLong(paramWrap.get(str).toString());
		}
		if("createTime".equals(str)){
			createTime = paramWrap.get(str).toString();
		}
           if("orderby".equals(str)){
               orderby = paramWrap.get(str).toString();
           }
           if("order".equals(str)){
               order = 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<Question> pageVo = questionService.getQuestionListPage(title,userId,createTime,status,orderby,order,p,rows);
		env.setVariable("question_page", builder.build().wrap(pageVo));
	} catch (Exception e) {
		env.setVariable("question_page", builder.build().wrap(null));
	}
	body.render(env.getOut());
}
 
Example 19
Source File: RenderTargetDirective.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
protected void executeTyped(Environment env, Map<String, TemplateModel> params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        Writer writer = env.getOut();

        // NOTE: this can only work if we already had a RenderWriter.
        // if not, don't even bother trying.
        if (writer instanceof RenderWriter) {
            Map<String, Object> context = ContextFtlUtil.getContext(env);
            WidgetRenderTargetState renderTargetState = WidgetRenderTargetExpr.getRenderTargetState(context);
            if (renderTargetState.isEnabled()) {
                String dirName = TransformUtil.getStringArg(params, "dirName");
                //TemplateHashModel dirArgs = (TemplateHashModel) params.get("dirArgs");

                String id = null;
                String name = null; // TODO?: this may not work as expected if we do this...
                // TODO: review
//                if (dirArgs != null) {
//                    TemplateScalarModel idModel = (TemplateScalarModel) dirArgs.get("id");
//                    if (idModel != null) {
//                        id = LangFtlUtil.getAsStringNonEscaping(idModel);
//                        if ("section".equals(dirName)) {
//                            TemplateScalarModel containerIdModel = (TemplateScalarModel) dirArgs.get("containerId");
//                            if (containerIdModel != null) {
//                                String containerId = LangFtlUtil.getAsStringNonEscaping(containerIdModel);
//                                if (UtilValidate.isNotEmpty(containerId)) {
//                                    id = containerId;
//                                }
//                            }
//                        }
//                    }
//                } else {
                id = TransformUtil.getStringNonEscapingArg(params, "id");
                name = TransformUtil.getStringNonEscapingArg(params, "name");
//                }

                String location = "unknown-location"; // FIXME
                ModelFtlWidget widget = new ModelFtlWidget(name, dirName, location, id);

                WidgetRenderTargetState.ExecutionInfo execInfo = renderTargetState.handleShouldExecute(widget, writer, context, null);
                if (!execInfo.shouldExecute()) {
                    return;
                }
                try {
                    if (body != null) {
                        body.render((Writer) execInfo.getWriterForElementRender());
                    }
                } finally {
                    execInfo.handleFinished(context); // SCIPIO: return logic
                }
                return;
            }
        }

        body.render(writer);
    }
 
Example 20
Source File: TemplateCustomMethods.java    From bbs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @param env
 * @param params 参数
 * @param loopVars 循环变量
 * @param body 指令内容体
 */
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars,
		TemplateDirectiveBody body) throws TemplateException, IOException {
	String referenceCode = "";//版块引用代码
	String templatesDir = templateService.findTemplateDir_cache();
	TemplateRunObject templateRunObject = TemplateThreadLocal.get();
	List<String> layoutFile = new ArrayList<String>();//布局文件
	Map<String,Object> parameter = new HashMap<String,Object>();//提交参数
	Map<String,Object> runtimeParameter = new HashMap<String,Object>();//运行时参数
	
    //取得当前正在运行的引入指令
    if(templateRunObject != null){
    	 referenceCode = templateRunObject.getReferenceCode();//引用代码
    	 layoutFile.addAll(templateRunObject.getLayoutFileList());//布局文件
    	 if(templateRunObject.getParameter() != null && templateRunObject.getParameter().size() >0){
    		 parameter.putAll(templateRunObject.getParameter());
    		 templateRunObject.getParameter().clear();
    	 }
    	 
    	 if(templateRunObject.getRuntimeParameter() != null && templateRunObject.getRuntimeParameter().size() >0){
    		 runtimeParameter.putAll(templateRunObject.getRuntimeParameter());
    	 }
    		  
     }
    
     //取得<@function parameter...></@function>的参数
     if(params != null && params.size() >0){
    	Iterator paramIter = params.entrySet().iterator();
		while(paramIter.hasNext()) {
			Map.Entry ent = (Map.Entry) paramIter.next();		
					
			if(ent.getValue() != null && !"".equals(ent.getValue().toString().trim())){
				parameter.put(ent.getKey().toString(), ent.getValue().toString().trim());
				
			}
		}
     }
    
	if(referenceCode != null && !"".equals(referenceCode)){
		 //模板路径名称(env.getTemplate().getName()方法已过时)
		String templatePathName = env.getCurrentTemplate().getName();
		
	    //模板文件名称  StringUtils.lastIndexOfIgnoreCase从后往前查,不区分大小写
		String name = templatePathName.substring(StringUtils.lastIndexOfIgnoreCase(templatePathName, "/")+1,templatePathName.lastIndexOf("."));//删除后缀名
		 
		
		
		Forum forum = templateService.findForum_cache(templatesDir,referenceCode);
    	if(forum != null){
    		
    		
    		StringBuffer modulePrefix = new StringBuffer("");//版块模板前缀     ProductRelated_Product_Page
    		String[] module_str = forum.getModule().split("_");
    		int i = 0;
    		for(String str :module_str){
    			modulePrefix.append(str);
    			if(i<2){
    				modulePrefix.append("_");
    			}else{
    				break;
    			}
    			i++;
    		}
    		
    		if(name.equals(forum.getModule()) && forum.getInvokeMethod().equals(1)){//1.引用代码
    			
    			
	    		if(layoutFile.contains(forum.getLayoutFile()) || forum.getLayoutType().equals(6)){
	    			env.setVariable(modulePrefix.toString(), getBeansWrapper().wrap(templateMain.templateObject(forum,parameter,runtimeParameter)));//引用代码为key  如:Product_Show_1 
			    	if(body != null){
			    		 body.render(env.getOut()); 
			    	}
	    		}
	    	}
	    } 
	}
}