@Component
public class RoleDirectiveModel implements TemplateDirectiveModel {
/**
*
* @param environment 环境变量
* @param params 指令参数(存储你所需要的值,随便是什么Key-Value你懂的)
* @param loopVars 循环变量 返回值
* @param templateDirectiveBody 指令内容
* 除了params外,其他的都能是Null。
* @throws TemplateException
* @throws IOException
*/
@Override
public void execute(Environment environment, Map params, TemplateModel[] loopVars, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
System.out.println("=========");
TemplateScalarModel user=(TemplateScalarModel)params.get("user");
TemplateScalarModel role=(TemplateScalarModel)params.get("role");
if("123456".equals(user.getAsString()) && "admin".equals(role.getAsString()) ){
loopVars[0]=TemplateBooleanModel.TRUE;
}
List otherRights=new ArrayList<>();
otherRights.add("add");
otherRights.add("update");
otherRights.add("delete");
loopVars[1]=new SimpleSequence(otherRights);
templateDirectiveBody.render(environment.getOut());
}
}
这是自定义指令的定义类
这是加载自定义指令的freemarker java配置类import com.example.demo.model.tag.RoleDirectiveModel;
import com.example.demo.model.tag.SortMethod;
import freemarker.template.TemplateModelException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
@Slf4j
@Configuration
public class FreeMarkerAutoConfiguration {
@Autowired
private freemarker.template.Configuration configuration;
@Autowired
private RoleDirectiveModel roleDirectiveModel;
@Autowired
private SortMethod sortMethod;
@PostConstruct
public void setSharedVariable() {
try {
//自定义标签
configuration.setSharedVariable("role", roleDirectiveModel);
configuration.setSharedVariable("sort_int",sortMethod);
} catch (Exception e) {
log.error("Custom tags failed to load:{}", e.getMessage());
}
}
}