Java 类freemarker.template.TemplateMethodModelEx 实例源码

项目:stampo    文件:FreemarkerRenderer.java   
private static void registerResourceBundleResolver(Map<String, Object> model, Locale locale, StampoGlobalConfiguration configuration) {
  model.put("message", new ResourceBundleModel(ResourceBundle.getBundle("messages", locale, configuration.getResourceBundleControl()), new BeansWrapperBuilder(Configuration.VERSION_2_3_22).build()));

  TemplateMethodModelEx messageWithBundle = (arguments) -> {
    if (arguments.size() < 2) {
      throw new IllegalArgumentException(
          "messageWithBundle must have at least 2 parameters, passed only " + arguments.size());
    }

    String bundleName = arguments.get(0).toString();
    String code = arguments.get(1).toString();

    List<Object> parameters = new ArrayList<>();
    for (int i = 2; i < arguments.size(); i++) {
      parameters.add(arguments.get(i));
    }

    return MessageFormat.format(
        ResourceBundle.getBundle(bundleName, locale, configuration.getResourceBundleControl()).getString(code),
        parameters.toArray());
  };

  model.put("messageWithBundle", messageWithBundle);

  TemplateMethodModelEx defaultOrLocale = (arguments) -> {
    String loc = arguments.get(0).toString();
    return configuration.getDefaultLocale().map(l -> l.toLanguageTag().equals(loc) ? "" : loc)
        .orElse(loc);
  };
  model.put("defaultOrLocale", defaultOrLocale);

  TemplateMethodModelEx switchToLocale = (arguments) -> {
    String localeToSwitch = arguments.get(0).toString();
    Path fileResourceOutputPath = (Path) model.get("fileResourceOutputPath");
    return PathUtils.switchToLocale(Locale.forLanguageTag(localeToSwitch), locale, fileResourceOutputPath, configuration);
  };

  model.put("switchToLocale", switchToLocale);
}