Java Code Examples for org.thymeleaf.context.Context#setVariables()

The following examples show how to use org.thymeleaf.context.Context#setVariables() . 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: EmailService.java    From jakduk-api with MIT License 6 votes vote down vote up
public void sendBulk(EmailPayload emailPayload) throws MessagingException {

		// Prepare the evaluation context
		final Context ctx = new Context(emailPayload.getLocale());
		ctx.setVariables(emailPayload.getBody());

		// Prepare message using a Spring helper
		final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
		final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");

		message.setSubject(emailPayload.getSubject());
		message.setTo(emailPayload.getRecipientEmail());

		// Create the HTML body using Thymeleaf
		final String htmlContent = this.htmlTemplateEngine.process(emailPayload.getTemplateName(), ctx);
		message.setText(htmlContent, true /* isHtml */);

		// Send email
		this.mailSender.send(mimeMessage);
	}
 
Example 2
Source File: HttpResourceThymeleaf.java    From ext-opensource-netty with Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected ByteBuf buildRes(String resPath, Map<String, Object> parameters) {
	if (!isThymeleafFile(resPath)) {
		
		return super.buildRes(resPath, parameters);
	} else {
		try {
			Context context = new Context();
			context.setVariables(parameters);

			if (!engine.isInitialized()) {
				ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
				resolver.setPrefix(this.getRootDir());
				//设置不缓存
				resolver.setCacheable(false);
				engine.setTemplateResolver(resolver);
			}

			String htmlContext = engine.process(resPath, context);
			return Unpooled.copiedBuffer(htmlContext, CharsetUtil.UTF_8);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}
}
 
Example 3
Source File: ThymeleafTemplateService.java    From spring-boot-email-tools with Apache License 2.0 6 votes vote down vote up
@Override
public
@NonNull
String mergeTemplateIntoString(final @NonNull String templateReference,
                               final @NonNull Map<String, Object> model)
        throws IOException, TemplateException {
    final String trimmedTemplateReference = templateReference.trim();
    checkArgument(!isNullOrEmpty(trimmedTemplateReference), "The given template is null, empty or blank");
    if (trimmedTemplateReference.contains("."))
        checkArgument(Objects.equals(getNormalizedFileExtension(trimmedTemplateReference), expectedTemplateExtension()),
                "Expected a Thymeleaf template file with extension '%s', while '%s' was given. To check " +
                        "the default extension look at 'spring.thymeleaf.suffix' in your application.properties file",
                expectedTemplateExtension(), getNormalizedFileExtension(trimmedTemplateReference));

    final Context context = new Context();
    context.setVariables(model);

    return thymeleafEngine.process(FilenameUtils.removeExtension(trimmedTemplateReference), context);
}
 
Example 4
Source File: ViewThymeleaf.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean render(RequestWeb req, View view)
{
  String viewName = view.name();

  if (! viewName.endsWith(".html")) {
    return false;
  }

  try {
    Context ctx = new Context();
    ctx.setVariables(view.map());

    req.type("text/html; charset=utf-8");

    _engine.process(viewName, ctx, req.writer());

    req.ok();
  }
  catch (Exception e) {
    req.fail(e);
  }

  return true;
}
 
Example 5
Source File: ThymeleafUtil.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 模板名称需要在 classpath:templates/plugin 下
 *
 * @param template  模板名称
 * @param variables 变量
 * @return 转换后的
 */
public static String process(String template, Map<String, Object> variables) {
    Context context = new Context();
    if (variables == null) {
        variables = new HashMap<>(10);
    }
    String normalize = FileUtil.normalize("plugin/" + template);
    // 用户变量
    UserModel userModel = BaseServerController.getUserModel();
    variables.put(LoginInterceptor.SESSION_NAME, userModel);
    context.setVariables(variables);
    ThymeleafUtil thymeleafUtil = SpringUtil.getBean(ThymeleafUtil.class);
    return thymeleafUtil.springTemplateEngine.process(normalize, context);
}
 
Example 6
Source File: EmailServiceImpl.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void sendMessageUsingThymeleafTemplate(
    String to, String subject, Map<String, Object> templateModel)
        throws MessagingException {
            
    Context thymeleafContext = new Context();
    thymeleafContext.setVariables(templateModel);
    
    String htmlBody = thymeleafTemplateEngine.process("template-thymeleaf.html", thymeleafContext);

    sendHtmlMessage(to, subject, htmlBody);
}
 
Example 7
Source File: ThymeleafTemplateEngine.java    From spark-template-engines with Apache License 2.0 5 votes vote down vote up
/**
* Process the specified template (usually the template name).
* Output will be written into a String that will be returned from calling this method,
* once template processing has finished.
* @param modelAndView model and view
* @param locale A Locale object represents a specific geographical, political, or cultural region
* @return processed template
*/
 public String render(ModelAndView modelAndView, Locale locale) {
     Object model = modelAndView.getModel();

     if (model instanceof Map) {
         Context context = new Context(locale);
         context.setVariables((Map<String, Object>) model);
         return templateEngine.process(modelAndView.getViewName(), context);
     } else {
         throw new IllegalArgumentException("modelAndView.getModel() must return a java.util.Map");
     }
 }
 
Example 8
Source File: ThymeleafTemplateProcessorImpl.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String process(String templateName, Map<String, Object> variables)
    throws TemplateException {
  final Context context = new Context();
  context.setVariables(variables);
  return templateEngine.process(templateName, context);
}
 
Example 9
Source File: WordprocessingMLThymeleafTemplate.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * 使用Thymeleaf模板引擎渲染模板
 * @param template :模板内容
 * @param variables :变量
 * @return {@link WordprocessingMLPackage} 对象
 * @throws Exception :异常对象
 */
@Override
public WordprocessingMLPackage process(String template, Map<String, Object> variables) throws Exception {
	// 创建模板输出内容接收对象
	StringWriter output = new StringWriter();
	//设置上下文参数
	Context ctx = new Context();
       ctx.setVariables(variables);
	// 使用Thymeleaf模板引擎渲染模板
	getEngine().process(template , ctx , output);
	//获取模板渲染后的结果
	String html = output.toString();
	//使用HtmlTemplate进行渲染
	return mlHtmlTemplate.process(html, variables);
}
 
Example 10
Source File: EmailServiceImpl.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
@Override
public void sendReplyEmail(String url, String htmlContent, String nickName, String email, ReplayEmail replayEmail) {
    Context context = new Context();
    //回复的内容
    context.setVariables(replayEmail.toMap());
    String emailContent = templateEngine.process("/mail/ReplyEmail", context);
    String title = "DimpleBlog 留言回复通知!";
    sendHtmlMail(email, title, emailContent);
}
 
Example 11
Source File: ThymeleafTest.java    From ext-opensource-netty with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 使用 Thymeleaf 渲染 HTML
 * @param template  HTML模板
 * @param params 参数
 * @return  渲染后的HTML
 */
public static String render(String template,Map<String,Object> params){
    Context context = new Context();
    context.setVariables(params);
    TemplateEngine engine=new TemplateEngine();
    
    StringTemplateResolver  resolver = new StringTemplateResolver();
    engine.setTemplateResolver(resolver);
    return engine.process(template,context);
}
 
Example 12
Source File: ThymeleafTemplateDelegate.java    From reactor-guice with Apache License 2.0 5 votes vote down vote up
@Override
public String template(Object handleObject, ModelMap modelMap, String templateName) {

    String controllerName = handleObject.getClass().getSimpleName();
    String templateDirectory = controllerName.toLowerCase().substring(0, controllerName.length() - "handle".length());
    templateResolver.setPrefix(this.getClass().getResource("/template/" + templateDirectory).getPath() + "/");

    TemplateEngine engine = new TemplateEngine();
    engine.setTemplateResolver(templateResolver);

    Context context = new Context();
    context.setVariables(modelMap);

    return engine.process(templateName, context);
}
 
Example 13
Source File: Test.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // 1.上下文
    Context context = new Context();
    //创建数据模型
    Map<String, Object> dataModel = new HashMap<String, Object>(1);
    dataModel.put("name", "青橙电商系统");
    context.setVariables(dataModel);
    // 2.准备文件
    File dest = new File("d:/test_out.html");
    // 3.生成页面
    try {
        PrintWriter writer = new PrintWriter(dest, "UTF-8");
        //模板解析器
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        //模板模型
        resolver.setTemplateMode(TemplateMode.HTML);
        //后缀
        resolver.setSuffix(".html");
        //创建模板引擎
        TemplateEngine engine = new TemplateEngine();
        //设置模板解析器
        engine.setTemplateResolver(resolver);
        //执行模板引擎
        engine.process("test", context, writer);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 14
Source File: ThymeleafTemplateHandler.java    From myexcel with Apache License 2.0 4 votes vote down vote up
@Override
protected <F> void render(Map<String, F> renderData, Writer out) throws Exception {
    Context context = new Context();
    context.setVariables(renderData);
    templateEngine.process(filePath, context, out);
}
 
Example 15
Source File: ThymeleafTemplateService.java    From c4sg-services with MIT License 4 votes vote down vote up
@Override
public String generateFromContext(Map<String, Object> mailContext, String template) {
	Context ctx = new Context();
	ctx.setVariables(mailContext);
	return engine.process(template, ctx);
}
 
Example 16
Source File: EmailServiceImpl.java    From konker-platform with Apache License 2.0 4 votes vote down vote up
@Override
public ServiceResponse<Status> send(String sender, 
								List<User> recipients, 
								List<User> recipientsCopied, 
								String subject,
								String templateName, 
								Map<String, Object> templateParam,
								Locale locale) {
	try {
		if (!Optional.ofNullable(sender).isPresent() || sender.isEmpty()) {
			return ServiceResponseBuilder.<Status>error().withMessage(Validations.SENDER_NULL.getCode()).build();
		}
		if (!Optional.ofNullable(recipients).isPresent() || recipients.isEmpty()) {
			return ServiceResponseBuilder.<Status>error().withMessage(Validations.RECEIVERS_NULL.getCode()).build();
		}
		if (!Optional.ofNullable(subject).isPresent() || subject.isEmpty()) {
			return ServiceResponseBuilder.<Status>error().withMessage(Validations.SUBJECT_EMPTY.getCode()).build();
		}
		if (!Optional.ofNullable(templateName).isPresent() || templateName.isEmpty()) {
			return ServiceResponseBuilder.<Status>error().withMessage(Validations.BODY_EMPTY.getCode()).build();
		}
		
		final Context ctx = new Context(locale);
		ctx.setVariables(templateParam);
		
		final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
		final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
		message.setSubject(subject);
		message.setFrom(sender);
		message.setTo(recipients.stream().map(r -> r.getEmail()).collect(Collectors.toList()).toArray(new String[0]));
		
		if (Optional.ofNullable(recipientsCopied).isPresent()) {
			message.setCc(recipientsCopied.stream().map(r -> r.getEmail()).collect(Collectors.toList()).toArray(new String[0]));
		}
		
		final String htmlContent = this.templateEngine.process(templateName, ctx);
		message.setText(htmlContent, true);
		
		this.mailSender.send(mimeMessage);
		
		return ServiceResponseBuilder.<Status>ok().build();
		
	} catch (MessagingException e) {
		return ServiceResponseBuilder.<Status>error()
			.withMessage(e.getMessage())
			.build();
	}
}
 
Example 17
Source File: ThymeleafServiceImpl.java    From purplejs with Apache License 2.0 4 votes vote down vote up
private String doRender( final ResourcePath view, final Map<String, Object> model )
{
    final Context context = new Context();
    context.setVariables( model );
    return this.engine.process( view.toString(), context );
}
 
Example 18
Source File: MailController.java    From parker with MIT License 4 votes vote down vote up
@ApiOperation("发送HTML格式的邮件")
@PostMapping("send/html")
public BaseResult sendHtml(@RequestBody MailHtmlMessageDto dto){
    BaseResult result = new BaseResult();

    if(StringUtils.isBlank(dto.getTo())){
        result.setData(0);
        result.setMessage("缺少收信人");
        return result;
    }

    if(StringUtils.isBlank(dto.getSubject())){
        result.setData(0);
        result.setMessage("缺少主题");
        return result;
    }

    MimeMessage mimeMessage = javaMailSender.createMimeMessage();

    try {
        // true表示需要创建一个multipart message
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        helper.setTo(dto.getTo());
        helper.setSubject(dto.getSubject());

        // 创建邮件正文
        Context context = new Context();
        if(StringUtils.isNotBlank(dto.getParams())){
            JSONObject params = JSONObject.parseObject(dto.getParams());
            context.setVariables(params);
        }
        String text = templateEngine.process(dto.getMailCode(), context);

        if(StringUtils.isNotBlank(text)){
            helper.setText(text, true);
        }else{
            result.setData(0);
            result.setMessage("缺少内容");
            return result;
        }

        javaMailSender.send(mimeMessage);
    } catch (Exception e) {
        result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        result.setMessage(e.getMessage());
        log.error("发送HTML格式的邮件参数错误{}", e.getMessage());
        e.printStackTrace();
    }
    return result;
}
 
Example 19
Source File: MailServiceImpl.java    From nimrod with MIT License 4 votes vote down vote up
@Override
public String loadHtmlTemplate(String templatePath, Map<String, Object> variables) {
    Context context = new Context();
    context.setVariables(variables);
    return templateEngine.process(templatePath, context);
}