动态模板解析器使用Thymeleaf

huangapple go评论78阅读模式
英文:

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 = &quot;&lt;h1&gt;Hi ${first_name} ${last_name}&lt;/h1&gt;&quot;;
Map&lt;String, Object&gt; 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
    }
}

它将渲染出 &lt;h1&gt;Hi Abel Lincon&lt;/h1&gt;

如果你想手动处理模板,你可以自动装配模板引擎并手动使用它:

@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:

&lt;h1 th:text=&quot;Hi ${first_name} ${last_name}&quot;&gt;&lt;/h1&gt;

and use it with a mvc controller that sets the variables in the model:

@Controller
public class HelloController {

    @GetMapping(&quot;/hello&quot;)
    public String handle(Model model) {
        model.addAttribute(&quot;first_name&quot;, &quot;Abel&quot;);
        model.addAttribute(&quot;last_name&quot;, &quot;Lincon&quot;);
        return &quot;mytemplate&quot;; //resolves to mytemplate.html
    }
}

And it will render &lt;h1&gt;Hi Abel Lincon&lt;/h1&gt;

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( &quot;mytemplate&quot;,
                        new Context( Locale.ENGLISH, Map.of(
                                &quot;first_name&quot;, &quot;Abel&quot;,
                                &quot;last_name&quot;, &quot;Lincon&quot;
                        )) );

答案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(&quot;/thymeleaf/&quot;);
        templateResolver.setCacheTTLMs(3600000L); // one hour
        templateResolver.setCacheable(true);
        this.templateEngine.setTemplateResolver(templateResolver);
    }

    public String getTemplate(String templateName, Map&lt;String, Object&gt; parameters) {
        Context ctx = new Context();
        if (parameters != null) {
            parameters.forEach((k, v) -&gt; {
                ctx.setVariable(k, v);
            });
        }
        return this.templateEngine.process(templateName, ctx).trim();
    }

}

This can then be called as follows for HTML templates:

HashMap&lt;String, Object&gt; values = new HashMap&lt;&gt;();
values.put(&quot;hello&quot;, &quot;hello everyone&quot;);
GenericTemplateEngine engine = new GenericTemplateEngine(TemplateMode.HTML);
String s = engine.getTemplate(&quot;hello_world.html&quot;, 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);

huangapple
  • 本文由 发表于 2020年10月14日 00:53:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64339712.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定