freemarker 自定义指令

freemarker 自定义指令,需要实现TemplateDirectiveModel 类中的
public void execute(Environment env, Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body) throws TemplateException, IOException 方法,改方法中的TemplateModel[] loopVars 怎么用呢?网上搜了半天也没看明白,请问这个参数怎么用,最好给个例子

给你一个例子
public class OperatorDirective implements TemplateDirectiveModel{

@Override
public void execute(Environment env, Map params, TemplateModel[] arg2,
        TemplateDirectiveBody body) throws TemplateException, IOException {
    String code = null;
    String roleId = null; 
    if(params.get("code") != null){
        SimpleScalar codeSimpleScalar = (SimpleScalar)params.get("code");
        code = codeSimpleScalar.getAsString();
    }
    if(params.get("roleId") != null){
        SimpleScalar roleIdSimpleScalar = (SimpleScalar)params.get("roleId");
        roleId = roleIdSimpleScalar.getAsString();
    }

    if(code == null)
        throw new TemplateException("code不能为空!",env);
    if(roleId == null)
        throw new TemplateException("roleId不能为空!",env);
    ModuleRoleService moduleRoleService = SpringContextUtil.getApplicationContextInstance().getBean("moduleRoleService", ModuleRoleService.class);
    if(moduleRoleService != null){
        boolean isPrevilege = moduleRoleService.findPrevilegeByCodeAndRoleId(code, new Long(roleId));
        if(isPrevilege){
            System.out.println("env.getOut()=="+env.getOut());
            body.render(env.getOut());
        }
    }

}

}

然后最好放到全局变量里去,这样的好处是是在模板里直接使用,要不然每次都需要导入,例如spring里可以这样配置

class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">

/

    <!-- 全局变量部分 -->
    <property name="freemarkerVariables">

            <entry key="previlegeModuleEnum" value-ref="previlegeModuleEnum" />
        </map>
    </property>

</bean>

最后在模板里使用
<@ operatorDirective roleId="data" code ="data"/>

哥们看这个:
[url]http://blog.csdn.net/laufu/article/details/6748617[/url]

  • @param loopVars an array that corresponds to the "loop variables", in
    • the order as they appear in the directive call. ("Loop variables" are out-parameters
    • that are available to the nested body of the directive; see in the Manual.)
    • You set the loop variables by writing this array. The length of the array gives the
    • number of loop-variables that the caller has specified.

如<#list 0..x as i>
大体意思就是loopVars存放的是循环变量 对嵌套body内是有效的 也就是说可以修改这个数组改变循环变量

再比如
<#list 0..x as i>
<#list 0..x as j> 那么这个数组的长度就是2

:wink: