英文:
Dynamic template resolver using Thymeleaf
问题
我们有一个需求,需要动态地解析 HTML 或文本模板。模板内容(一个字符串)带有变量占位符,这些内容将存储在数据库中。
我们需要根据实际变量的值在需求时动态地解析它们,并获得最终的字符串内容。
示例:(不是完整的代码)
String myHtmlTemplateContent = "<h1>Hi ${first_name} ${last_name}</h1>";
Map<String, Object> myMapWithValues = ..;
engine.resolve(myHtmlTemplateContent, myMapWithValues);
如果我们能够使用 Thymeleaf 来解析,或者是否可能使用 Thymeleaf 模板引擎来实现,将会非常有帮助。
英文:
We have a requirement to dynamically resolve html or text templates. The template content (a string) with variable place holders will be available in database.
We have to resolve them dynamically on demand with the actual values for the variables and get the final string content.
Example: (not a complete code)
String myHtmlTemplateContent = "<h1>Hi ${first_name} ${last_name}</h1>";
Map<String, Object> myMapWithValues = ..;
engine.resolve(myHtmlTemplateContent , myMapWithValues );
Will be helpful if we have a way to resolve using thymeleaf or is it possible using thymeleaf template engine.
答案1
得分: 2
你需要创建一个Thymeleaf模板 mytemplate.html
,其中包含:
<h1 th:text="Hi ${first_name} ${last_name}"></h1>
并使用一个MVC控制器来设置模型中的变量:
@Controller
public class HelloController {
@GetMapping("/hello")
public String handle(Model model) {
model.addAttribute("first_name", "Abel");
model.addAttribute("last_name", "Lincon");
return "mytemplate"; //resolves to mytemplate.html
}
}
它将渲染出 <h1>Hi Abel Lincon</h1>
。
如果你想手动处理模板,你可以自动装配模板引擎并手动使用它:
@Autowired
SpringTemplateEngine templateEngine;
String emailContent = templateEngine.process("mytemplate",
new Context(Locale.ENGLISH, Map.of(
"first_name", "Abel",
"last_name", "Lincon"
)));
英文:
You need to create a thymeleaf template mytemplate.html
containing:
<h1 th:text="Hi ${first_name} ${last_name}"></h1>
and use it with a mvc controller that sets the variables in the model:
@Controller
public class HelloController {
@GetMapping("/hello")
public String handle(Model model) {
model.addAttribute("first_name", "Abel");
model.addAttribute("last_name", "Lincon");
return "mytemplate"; //resolves to mytemplate.html
}
}
And it will render <h1>Hi Abel Lincon</h1>
If you want to manually process a template, you could autowire the template engine and use it manually:
@Autowired SpringTemplateEngine templateEngine;
String emailContent = templateEngine.process( "mytemplate",
new Context( Locale.ENGLISH, Map.of(
"first_name", "Abel",
"last_name", "Lincon"
)) );
答案2
得分: 0
我使用了以下方法:
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.context.Context;
import java.util.Map;
public class GenericTemplateEngine {
private final TemplateEngine templateEngine;
public GenericTemplateEngine(TemplateMode templateMode) {
templateEngine = new org.thymeleaf.TemplateEngine();
ClassLoaderTemplateResolver templateResolver
= new ClassLoaderTemplateResolver(Thread
.currentThread().getContextClassLoader());
templateResolver.setTemplateMode(templateMode);
templateResolver.setPrefix("/thymeleaf/");
templateResolver.setCacheTTLMs(3600000L); // one hour
templateResolver.setCacheable(true);
this.templateEngine.setTemplateResolver(templateResolver);
}
public String getTemplate(String templateName, Map<String, Object> parameters) {
Context ctx = new Context();
if (parameters != null) {
parameters.forEach((k, v) -> {
ctx.setVariable(k, v);
});
}
return this.templateEngine.process(templateName, ctx).trim();
}
}
然后可以如下调用用于HTML模板:
HashMap<String, Object> values = new HashMap<>();
values.put("hello", "hello everyone");
GenericTemplateEngine engine = new GenericTemplateEngine(TemplateMode.HTML);
String s = engine.getTemplate("hello_world.html", values);
System.out.println(s);
地图中的值加载到Thymeleaf上下文中,然后与模板一起传递给引擎类。
如果您有文本模板而不是HTML模板,则可以使用以下内容:
new GenericTemplateEngine(TemplateMode.TEXT);
英文:
I have used the following approach:
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.context.Context;
import java.util.Map;
public class GenericTemplateEngine {
private final TemplateEngine templateEngine;
public GenericTemplateEngine(TemplateMode templateMode) {
templateEngine = new org.thymeleaf.TemplateEngine();
ClassLoaderTemplateResolver templateResolver
= new ClassLoaderTemplateResolver(Thread
.currentThread().getContextClassLoader());
templateResolver.setTemplateMode(templateMode);
templateResolver.setPrefix("/thymeleaf/");
templateResolver.setCacheTTLMs(3600000L); // one hour
templateResolver.setCacheable(true);
this.templateEngine.setTemplateResolver(templateResolver);
}
public String getTemplate(String templateName, Map<String, Object> parameters) {
Context ctx = new Context();
if (parameters != null) {
parameters.forEach((k, v) -> {
ctx.setVariable(k, v);
});
}
return this.templateEngine.process(templateName, ctx).trim();
}
}
This can then be called as follows for HTML templates:
HashMap<String, Object> values = new HashMap<>();
values.put("hello", "hello everyone");
GenericTemplateEngine engine = new GenericTemplateEngine(TemplateMode.HTML);
String s = engine.getTemplate("hello_world.html", values);
System.out.println(s);
The values in the Map are loaded into the Thymeleaf context, and then passed, along with a template, to the engine class.
If you have a text template instead of an HTML template, then you would use the following:
new GenericTemplateEngine(TemplateMode.TEXT);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论