freemarker中使用String字符串作为模板

    在日常开发中,我们有时候需要发送短信、邮件等通知,但是这些通知的内容通常都是动态的,而且可能会发生变动,为了程序的灵活性,我们通常会将通知的内容配置在页面上,然后后台通过渲染这些模板,来获取具体的内容。而 freemarker 正好可以帮助我们来完整模板的渲染这一步。

需求:
    1、给定一个字符串模板,渲染出内容
    2、修改这个字符串模板,然后再次渲染

实现要点:
    1、模板的加载器需要使用 StringTemplateLoader
    2、模板不可使用 Configuration.getTemplate,而应该使用 new Template

    3、StringTemplateLoader 上的一段注释

 
完整代码如下:

@Test
	public void test001() throws Exception {
		String templateName = "hello-template";
		String templateValue = "hello,${name}";
		Configuration configuration = configuration();
		processTemplate(configuration, templateName, templateValue);
		// -------------------- 进行模板的修改 ------------------------
		templateValue = "hello,${name},我今年,${age}岁.";
		processTemplate(configuration, templateName, templateValue);
	}

	/**
	 * 解析模板
	 *
	 * @param configuration
	 * @param templateName
	 * @throws IOException
	 * @throws TemplateException
	 */
	private void processTemplate(Configuration configuration, String templateName, String templateValue) throws IOException, TemplateException {
		Map<String, Object> root = new HashMap<>(4);
		root.put("name", "你好");
		root.put("age", 25);
		StringWriter stringWriter = new StringWriter();
		Template template = new Template(templateName, templateValue, configuration);
		template.process(root, stringWriter);
		System.out.println(stringWriter.toString());
	}

	/**
	 * 配置 freemarker configuration
	 *
	 * @return
	 */
	private Configuration configuration() {
		Configuration configuration = new Configuration(Configuration.VERSION_2_3_27);
		StringTemplateLoader templateLoader = new StringTemplateLoader();
		configuration.setTemplateLoader(templateLoader);
		configuration.setDefaultEncoding("UTF-8");
		return configuration;
	}

 

执行结果:

 

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值