【问题标题】:Unable to use expressions in Thymeleaf / Spring4无法在 Thymeleaf / Spring4 中使用表达式
【发布时间】:2015-03-20 06:08:45
【问题描述】:

在使用 Tiles 之后,我想尝试使用 Thymeleaf 模板,但是,我似乎根本无法在 HTML 页面中使用任何表达式。

我已经尝试使用项目启动器使用快速启动 Spring MVC,并且在渲染到 jsp 时一切正常,但没有使用带有 Thymeleaf 的 HTML - 显示了 HTML 页面,所以它显然在一定程度上可以工作,但所有表达式显示为简单文本且未计算。

这是 servlet-context.xml 的 Thymeleaf 部分:

<beans:bean id="templateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
    <beans:property name="prefix" value="/WEB-INF/templates/" />
    <beans:property name="suffix" value=".html" />
    <beans:property name="templateMode" value="HTML5" />
</beans:bean>
<beans:bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
    <beans:property name="templateResolver" ref="templateResolver" />
    <beans:property name="additionalDialects">
        <beans:set>
        <beans:bean class="nz.net.ultraq.thymeleaf.LayoutDialect" />
        </beans:set>
    </beans:property>
</beans:bean>
<beans:bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
    <beans:property name="templateEngine" ref="templateEngine" />
</beans:bean>

控制器只是从快速启动 MVC 模板中生成的一个:

@Controller
public class HomeController {

@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {        
    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

    String formattedDate = dateFormat.format(date);
    model.addAttribute("serverTime", formattedDate );
    return "home";
    }
}

HTML 只是从带有额外 Thymleaf 表达式的 jsp 中复制过来的:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1"/>
<title>Insert title here</title>
</head>
<body>
<p>  (HTML)The time on the server is ${serverTime}. </p>
#{serverTime}

<h1>th:text:="#{serverTime}"</h1>

</body>
</html>

关于我在这里缺少什么的任何想法?谢谢

【问题讨论】:

    标签: spring spring-mvc thymeleaf


    【解决方案1】:

    问题和你的html有关,Thymeleaf使用标准方言定义了以th:开头的html属性

    您的 html 正文应如下所示:

    <body>
    <p>The time on the server is <span th:text="${serverTime}">time</span>.</p>
    
    <h1 th:text="${serverTime}">Time again!</h1>
    
    </body>
    

    我推荐你阅读教程“Using Thymeleaf

    【讨论】:

    • 谢谢帕特里克,但我已经尝试过了——很抱歉,但我发布的 html 示例只是所做的众多尝试之一,而且有点草率。我已经阅读了您建议的教程(以及其他一些教程),甚至完全复制示例也会产生相同的结果。编辑:对不起,我的意思是如果像你建议的那样包含在一个 html 标记中,那么它们就会被完全省略。
    • 我删除了额外的 LayoutDialect,现在一切似乎都正常了。
    • 好消息!我错过了附加方言的那一行。一些附加信息:正如您提到的您以前使用过 Tiles,您可以使用 Thymeleaf Tiles Integration (thymeleaf.org/doc/articles/layouts.html),它工作得非常好。
    • 我肯定会研究 Tiles 集成 - 我会将 LayoutDialect 留作另一天的战斗!再次感谢您的帮助。
    猜你喜欢
    • 2014-07-21
    • 1970-01-01
    • 2016-01-21
    • 2017-03-28
    • 2017-10-19
    • 2016-01-16
    • 1970-01-01
    • 2013-04-13
    • 2018-04-02
    相关资源
    最近更新 更多