Java Code Examples for freemarker.template.Configuration#setNumberFormat()

The following examples show how to use freemarker.template.Configuration#setNumberFormat() . 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: Freemarker.java    From freeacs with MIT License 6 votes vote down vote up
/**
 * Inits the freemarker.
 *
 * @return the configuration
 */
public static Configuration initFreemarker() {
  try {
    Configuration config = new Configuration();
    config.setTemplateLoader(new ClassTemplateLoader(Freemarker.class, "/templates"));
    config.setTemplateUpdateDelay(0);
    config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
    config.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
    config.setDefaultEncoding("ISO-8859-1");
    config.setOutputEncoding("ISO-8859-1");
    config.setNumberFormat("0");
    config.setSetting("url_escaping_charset", "ISO-8859-1");
    config.setLocale(Locale.ENGLISH);
    setAutoImport(config);
    setSharedVariables(config);
    return config;
  } catch (Throwable e) {
    throw new RuntimeException("Could not initialise Freemarker configuration", e);
  }
}
 
Example 2
Source File: EasyUtils.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
/**
 * log4j里加 log4j.logger.freemarker=fatal 过滤掉FM自身的error Log
 */
public static String fmParse( String str, Map<String, ?> data, Writer out, Configuration cfg ) {
	try {
		cfg.setNumberFormat("#"); // 防止数字类格式化,eg: 1000 变 1,000
     Template tl = new Template("t.ftl", new StringReader(str), cfg);
     tl.setEncoding("UTF-8");
     tl.process(data, out);
     str = out.toString();
     out.flush();
     
     return str;
    } 
    catch (Exception e) {
    	String errorMsg = "FM-parse-error:" + e.getMessage();
 	log.error(errorMsg);
 	log.debug("template = " + str + ", data = " + data);
 	
 	return errorMsg;
 }
}
 
Example 3
Source File: TemplateProcessor.java    From contribution with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Generates output file with release notes using FreeMarker.
 *
 * @param variables the map which represents template variables.
 * @param outputFile output file.
 * @param templateFileName the optional file name of the template.
 * @param defaultResource the resource file name to use if no file name was given.
 * @throws IOException if I/O error occurs.
 * @throws TemplateException if an error occurs while generating freemarker template.
 */
public static void generateWithFreemarker(Map<String, Object> variables, String outputFile,
        String templateFileName, String defaultResource) throws IOException, TemplateException {

    final Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
    configuration.setDefaultEncoding("UTF-8");
    configuration.setLocale(Locale.US);
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    configuration.setNumberFormat("0.######");

    final StringTemplateLoader loader = new StringTemplateLoader();
    loader.putTemplate(TEMPLATE_NAME, loadTemplate(templateFileName, defaultResource));
    configuration.setTemplateLoader(loader);

    final Template template = configuration.getTemplate(TEMPLATE_NAME);
    try (Writer fileWriter = new OutputStreamWriter(
            new FileOutputStream(outputFile), StandardCharsets.UTF_8)) {
        template.process(variables, fileWriter);
    }
}
 
Example 4
Source File: FreemarkerTemplateEngineFactory.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
    Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
    configuration.setDefaultEncoding("utf-8");
    configuration.setLogTemplateExceptions(true);
    configuration.setNumberFormat("computer");
    configuration.setOutputFormat(XHTMLOutputFormat.INSTANCE);
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    configuration.setTemplateLoader(new SpringTemplateLoader(this.resourceLoader, this.resourceLoaderPath));

    if (this.shouldCheckForTemplateModifications) {
        configuration.setTemplateUpdateDelayMilliseconds(1000);
    } else {
        configuration.setTemplateUpdateDelayMilliseconds(Long.MAX_VALUE);
    }

    this.configuration = configuration;
}
 
Example 5
Source File: FreeMarkerConfigFactory.java    From youran with Apache License 2.0 5 votes vote down vote up
/**
 * 构建freemarker配置
 *
 * @param templatePO
 * @return (freemarker配置 , 模板内部版本号 , 模板目录地址)
 */
private Triple<Configuration, Integer, String> buildTriple(CodeTemplatePO templatePO) {
    String templateDir = dataDirService.getTemplateRecentDir(templatePO);
    LOGGER.info("开始构建FreeMarker Configuration,templateId={},innerVersion={},模板文件输出目录:{}",
        templatePO.getTemplateId(), templatePO.getInnerVersion(), templateDir);
    // 把模板输出到目录
    templateFileOutputService.outputTemplateFiles(templatePO.getTemplateFiles(), templateDir);

    Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
    try {
        cfg.setDirectoryForTemplateLoading(new File(templateDir));
    } catch (IOException e) {
        LOGGER.error("模板目录设置异常", e);
        throw new BusinessException("模板目录设置异常");
    }
    cfg.setNumberFormat("#");
    // 设置可访问的静态工具类
    cfg.setSharedVariable("MetaConstType", metaConstTypeModel);
    cfg.setSharedVariable("JFieldType", jFieldTypeModel);
    cfg.setSharedVariable("QueryType", queryTypeModel);
    cfg.setSharedVariable("EditType", editTypeModel);
    cfg.setSharedVariable("MetaSpecialField", metaSpecialFieldModel);
    cfg.setSharedVariable("PrimaryKeyStrategy", primaryKeyStrategyModel);
    cfg.setSharedVariable("CommonTemplateFunction", commonTemplateFunctionModel);
    cfg.setSharedVariable("JavaTemplateFunction", javaTemplateFunctionModel);
    cfg.setSharedVariable("SqlTemplateFunction", sqlTemplateFunctionModel);
    return Triple.of(cfg, templatePO.getInnerVersion(), templateDir);
}
 
Example 6
Source File: Generator.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Configuration newFreeMarkerConfiguration(List<File> templateRootDirs,
                                                               String defaultEncoding,
                                                               String templateName)
                throws IOException {
            Configuration conf = new Configuration();

            FileTemplateLoader[] templateLoaders = new FileTemplateLoader[templateRootDirs.size()];
            for (int i = 0; i < templateRootDirs.size(); i++) {
                templateLoaders[i] = new FileTemplateLoader((File) templateRootDirs.get(i));
            }
            MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(templateLoaders);

            conf.setTemplateLoader(multiTemplateLoader);
            conf.setNumberFormat("###############");
            conf.setBooleanFormat("true,false");
            conf.setDefaultEncoding(defaultEncoding);

            final String macro_include_ftl ="macro.include.ftl";
            String autoIncludes = new File(new File(templateName).getParent(),macro_include_ftl).getPath();
            List<String> availableAutoInclude = TemplateHelpers.getAvailableAutoInclude(conf, Arrays.asList(macro_include_ftl,autoIncludes));
            conf.setAutoIncludes(availableAutoInclude);
            GLogger.info("[set Freemarker.autoIncludes]"+availableAutoInclude+" for templateName:"+templateName);

//            GLogger.info(templateName);
//            List<String> autoIncludes = getParentPaths(templateName, "macro.include.ftl");
//            GLogger.info(autoIncludes.toString());
//            List<String> availableAutoInclude = TemplateHelpers.getAvailableAutoInclude(
//                conf, autoIncludes);
            conf.setAutoIncludes(availableAutoInclude);

            GLogger.trace("set Freemarker.autoIncludes:" + availableAutoInclude
                    + " for templateName:" + templateName + " autoIncludes:" + autoIncludes);
            return conf;
        }
 
Example 7
Source File: FreemarkerResultHandler.java    From oxygen with Apache License 2.0 5 votes vote down vote up
FreemarkerResolver() {
  cfg = new Configuration(Configuration.getVersion());
  cfg.setDefaultEncoding(StandardCharsets.UTF_8.name());
  cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
  cfg.setClassForTemplateLoading(Bootstrap.class,
      WebConfigKeys.VIEW_PREFIX_FREEMARKER.getValue());
  cfg.setNumberFormat(Strings.OCTOTHORP);
  if (WebConfigKeys.VIEW_CACHE.castValue(boolean.class)) {
    cfg.setCacheStorage(new MruCacheStorage(20, 250));
  } else {
    cfg.unsetCacheStorage();
  }
}
 
Example 8
Source File: FreemarkerConfig.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
	 * 
	 * @param httpConfig
	 * @param root
	 * @return
	 * @throws IOException
	 */
	private Configuration createConfiguration(HttpConfig httpConfig, String root) throws IOException {
		if (httpConfig.getPageRoot() == null) {
			return null;
		}

		if (configurationCreater != null) {
			return configurationCreater.createConfiguration(httpConfig, root);
		}

		Configuration cfg = new Configuration(Configuration.getVersion());

		if (httpConfig.isPageInClasspath()) {
			cfg.setClassForTemplateLoading(this.getClass(), "/" + root/**.substring("classpath:".length())*/
			);
			//cfg.setClassForTemplateLoading(FreemarkerUtil.class, "/template");
		} else {
			cfg.setDirectoryForTemplateLoading(new File(root));
		}
		cfg.setDefaultEncoding(httpConfig.getCharset());
		//		cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		cfg.setLogTemplateExceptions(false);
		cfg.setWrapUncheckedExceptions(true);
		cfg.setTemplateExceptionHandler(ShortMessageTemplateExceptionHandler.me);
		cfg.setLocale(Locale.SIMPLIFIED_CHINESE);
		cfg.setNumberFormat("#");
//		cfg.setClassicCompatible(true);
		return cfg;
	}
 
Example 9
Source File: FreeMarkerConfigExtend.java    From belling-admin with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws IOException, TemplateException {
	super.afterPropertiesSet();
	Configuration cfg = this.getConfiguration();
	cfg.setSharedVariable("shiro", new ShiroTags());// shiro标签
	cfg.setNumberFormat("#");// 防止页面输出数字,变成2,000
	// 可以添加很多自己的要传输到页面的[方法、对象、值]
}
 
Example 10
Source File: BaseDocumentationTest.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void loadTemplates() {
  loader = new ClassTemplateLoader(
      BaseDocumentationTest.class,
      "templates"
  );

  configuration = new Configuration(Configuration.getVersion());
  configuration.setDefaultEncoding("UTF-8");
  configuration.setTemplateLoader(loader);
  configuration.setObjectWrapper(new BeansWrapper(Configuration.getVersion()));
  configuration.setNumberFormat("computer");
}
 
Example 11
Source File: OutMsgXmlBuilder.java    From jfinal-weixin with Apache License 2.0 5 votes vote down vote up
private static Configuration initFreeMarkerConfiguration() {
	Configuration config = new Configuration();
	StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
	initStringTemplateLoader(stringTemplateLoader);
	config.setTemplateLoader(stringTemplateLoader);
	
	// 模板缓存更新时间,对于OutMsg xml 在类文件中的模板来说已有热加载保障了更新
       config.setTemplateUpdateDelay(999999);
       // - Set an error handler that prints errors so they are readable with
       //   a HTML browser.
       // config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
       config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
       
       // - Use beans wrapper (recommmended for most applications)
       config.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
       // - Set the default charset of the template files
       config.setDefaultEncoding(encoding);		// config.setDefaultEncoding("ISO-8859-1");
       // - Set the charset of the output. This is actually just a hint, that
       //   templates may require for URL encoding and for generating META element
       //   that uses http-equiv="Content-type".
       config.setOutputEncoding(encoding);			// config.setOutputEncoding("UTF-8");
       // - Set the default locale
       config.setLocale(Locale.getDefault() /* Locale.CHINA */ );		// config.setLocale(Locale.US);
       config.setLocalizedLookup(false);
       
       // 去掉int型输出时的逗号, 例如: 123,456
       // config.setNumberFormat("#");		// config.setNumberFormat("0"); 也可以
       config.setNumberFormat("#0.#####");
       config.setDateFormat("yyyy-MM-dd");
       config.setTimeFormat("HH:mm:ss");
       config.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
	return config;
}
 
Example 12
Source File: PluginFreeMarkerConfigurer.java    From onetwo with Apache License 2.0 4 votes vote down vote up
protected void postProcessConfiguration(Configuration config) throws IOException, TemplateException {
	config.setObjectWrapper(INSTANCE);
	config.setSetting("classic_compatible", "true");
	//默认不格式化数字
	config.setNumberFormat("#");
}
 
Example 13
Source File: FreemarkerTemplateEngine.java    From pippo with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Application application) {
    super.init(application);

    Router router = getRouter();
    PippoSettings pippoSettings = getPippoSettings();

    configuration = new Configuration(Configuration.VERSION_2_3_21);
    configuration.setDefaultEncoding(PippoConstants.UTF8);
    configuration.setOutputEncoding(PippoConstants.UTF8);
    configuration.setLocalizedLookup(true);
    configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, getTemplatePathPrefix());

    // We also do not want Freemarker to chose a platform dependent
    // number formatting. Eg "1000" could be printed out by FTL as "1,000"
    // on some platforms.
    // See also:
    // http://freemarker.sourceforge.net/docs/app_faq.html#faq_number_grouping
    configuration.setNumberFormat("0.######"); // now it will print 1000000

    if (pippoSettings.isDev()) {
        configuration.setTemplateUpdateDelayMilliseconds(0); // disable cache
    } else {
        // never update the templates in production or while testing...
        configuration.setTemplateUpdateDelayMilliseconds(Integer.MAX_VALUE);

        // Hold 20 templates as strong references as recommended by:
        // http://freemarker.sourceforge.net/docs/pgui_config_templateloading.html
        configuration.setCacheStorage(new freemarker.cache.MruCacheStorage(20, Integer.MAX_VALUE));
    }

    // set global template variables
    configuration.setSharedVariable("contextPath", new SimpleScalar(router.getContextPath()));
    configuration.setSharedVariable("appPath", new SimpleScalar(router.getApplicationPath()));

    webjarResourcesMethod = new WebjarsAtMethod(router);
    publicResourcesMethod = new PublicAtMethod(router);

    // allow custom initialization
    init(application, configuration);
}