简体   繁体   English

如何访问 thymeleaf 中对象属性的属性?

[英]How to access attribute of attribute of object in thymeleaf?

Say I want to access an object that is called post.假设我想访问一个名为 post 的对象。 Post has a instance variable called Category of type Category. Post 有一个名为 Category 类型的实例变量。

In the Java controller class在 Java 控制器类中

model.addAttribute("posts", postRepository.findPostsByUser(user));

In the thymeleaf html file I have在 thymeleaf html 文件中,我有

<tr data-th-each="post : ${posts}">

I am wondering if it is it possible to access the below?我想知道是否可以访问以下内容?

{post.category.name}

For clarification I have included the java classes below.为了澄清起见,我在下面包含了 java 类。 Each instance has associated setters and getters.每个实例都有关联的 setter 和 getter。

@Entity
public class Post {

@ManyToOne
@JoinColumn(name = "category_id")
private Category category;


@Entity
public class Category {

private String name;

I think you need to change your entity code 我认为您需要更改实体代码

@Entity
public class Post {

   private Category category;

   @ManyToOne(cascade = CascadeType.ALL)
   @JoinColumn(name = "category_id", nullable = false)
   public Category getCategory () {
     return this.category;
   }

   public void setCategory (Category category ) {
     this.category = category ;
   }

}

you need implement thymeleaf html page as per following 您需要按照以下方法实现thymeleaf html页面

<tr th:each="post : ${posts}">
   <td> <span th:utext="{post.category.name}" /></td>
</tr>

Hope its help to you! 希望对您有帮助!

you have to make a condition:你必须提出一个条件:

<tr th:each="post:${posts}">
    <td th:text="${post.category}!=null? ${post.category.name}:''"></td>
</tr>

:) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM