【问题标题】:pre processing in thymeleaf with context variable带有上下文变量的thymeleaf中的预处理
【发布时间】:2017-11-24 09:59:06
【问题描述】:

我得到一个已经有如下百里香标签的字符串:

String html = "<span th:text="${fisrtText}"></span> Indicative Terms for a <span th:text="${currency}"></span><span th:text="${amount}"></span>M <span th:text="${type}"></span> Facility"; 

我将上面的字符串设置为上下文变量:

context.setVariable("topSection", html);

我将上下文变量设置为用于替换上述字符串中的标签的值:

org.thymeleaf.context.Context context = new org.thymeleaf.context.Context();    
context.setVariable("fisrtText", "This is fisrt Text");
context.setVariable("currency", "$");
context.setVariable("amount", 256.10);
context.setVariable("type", "Loan");

现在在 template.html 我试图得到它如下:

<span th:utext="@{__${topSection}__}"></span>

我希望将 html 字符串替换为上下文中可用的值。但它返回与它相同的 html 没有任何处理:

<span th:text="${fisrtText}"></span> Indicative Terms for a <span th:text="${currency}"></span><span th:text="${amount}"></span>M <span th:text="${type}"></span> Facility"

任何帮助将不胜感激。

【问题讨论】:

    标签: thymeleaf preprocessor


    【解决方案1】:

    最好使用多个模板引擎 bean,一个用于字符串,另一个用于资源 HTML 文件。

    1) 对于资源文件

        @Bean(name ="templateEngine")       
        public SpringTemplateEngine getTemplateEngine() {
          SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    
          templateEngine.setTemplateResolver(new ClassLoaderTemplateResolver(););
          templateEngine.setMessageSource(messageSource);
          templateEngine.setTemplateEngineMessageSource(messageSource);
          return templateEngine;
       }
    

    您可以为 ClassLoaderTemplateResolver 设置前缀和后缀。

    2) 字符串模板解析器:

    @Bean(name ="stringTemplateEngine")     
        public SpringTemplateEngine getTemplateEngine() {
          SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    
          templateEngine.setTemplateResolver(new StringTemplateResolver(););
          return templateEngine;
       }
    

    现在首先使用 stringTemplateEngine 解析带有 thymeleaf 标签的字符串变量。

    String html = "<span th:text="${fisrtText}"></span>";
    String parsedHtml = stringTemplateEngine.process(html,context);
    

    现在将 ParsedHtml 放在上下文中。

    context.setVariable("topSection", parsedHtml);
    

    那么正如@holmis83 建议的那样,直接在模板中访问你的变量

    <span th:utext="${topSection}"></span>
    

    【讨论】:

      【解决方案2】:

      @{...} 是一个链接 URL 表达式。我认为您想使用 变量表达式 ${...}

      您的代码已调整:

      <span th:utext="${__${topSection}__}"></span>
      

      请注意,${topSection} 必须计算为表达式,它不能是任意 Thymeleaf 标记(例如 th:text)。

      【讨论】:

      • 在将 @ 更改为 $ 之后,现在它给了我一个解析错误:
      • 我将 html 缩减为一个带有一个 th:text 变量的跨度。原因:org.springframework.expression.spel.SpelParseException: Expression [] @0: EL1070E: Problem parsing left operand
      • @RamDuttShukla 正如我在上一段中所写,它必须是一个表达式,你不能使用预处理器来解析 Thymeleaf 标记。
      最近更新 更多