如何在Thymeleaf中水平获取数据库结果(每行4条记录)

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

how to get the result of database in thymleaf horizontally (4 records in a row)

问题

请大家帮助我在Thymeleaf中以横向方式获取数据库(MySQL)的结果(每行4条记录),然后下一行再次4条记录。当我添加新产品时,它会在Thymeleaf中的最后一个结果旁边再次添加结果。

如果需要更多信息,请告诉我。我是编程新手,想要学习。

控制器代码

@GetMapping("/product")
public ModelAndView getProduct() {

    ModelAndView model = new ModelAndView();

    List<Product> product= pRepo.findAll();

    model.addObject("products", product);
    model.setViewName("product");

    return model;
}

Thymeleaf代码

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body style="background-color:#F0F3F4;">

<div>
    <table>
        <tr th:each="product, iterStat : ${products}">
            <div class="card" style="align-items: center;">
                <img th:src="@{'/uploads/' + ${product.filename}}" alt="product name" width="150" height="150" />
                <h2 th:text="${product.prodName}"></h2>
                <p th:text="${product.prodDesc}" />
                <p th:text="'₹ ' + ${product.price}" />
                <p><input type="button" value="Add to Cart" /></p>
            </div>
            <th:block th:if="${iterStat.count % 4 == 0}"><br /></th:block>
        </tr>
    </table>
</div>

</body>
</html>

我正在尝试以适当的视图显示数据库中的产品列表,就像我在上面说的那样。

参考输出示例:点击这里查看图片
但是我只得到了单列的结果。

英文:

Please, someone, help me to get the result of the database(MySQL) in thymleaf horizontally (4 records in each row) and then next line again 4 rows. when I add a new product it will again add result in beside the last result in Thymleaf.

If any more information is required please let me know. I'm new in programming and wanted to learn.

Controller code

@GetMapping(&quot;/product&quot;)
public ModelAndView getProduct() {
	
	ModelAndView model = new ModelAndView();
	
	List&lt;Product&gt; product= pRepo.findAll();
	
	model.addObject(&quot;products&quot;, product);
	model.setViewName(&quot;product&quot;);
	
	return model;
}

Thymleaf code

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  max-width: 300px;
  margin: auto;
  text-align: center;
  font-family:cursive;

}

.price {
  color: grey;
  font-size: 24px;
}

.card input {
  border: none;
  outline: 0;
  padding: 12px;
  color: white;
  background-color: #000;
  text-align: center;
  cursor: pointer;
  width: 100%;
  font-size: 18px;
}

.card input:hover {
  opacity: 0.8;
}

.card img:hover {
  -ms-transform: scale(1); /* IE 9 */
  -webkit-transform: scale(1); /* Safari 3-8 */
  transform: scale(2.5); 
}

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html xmlns:th=&quot;http://www.thymeleaf.org&quot;&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;ISO-8859-1&quot;&gt;
    &lt;title&gt;Home&lt;/title&gt;

  &lt;/head&gt;
  &lt;body style=&quot;background-color:#F0F3F4;&quot;&gt;
    
    &lt;div&gt;
      &lt;table&gt;	
          &lt;tr th:each=&quot;product: ${products}&quot;&gt;

              &lt;div class=&quot;card&quot; style=&quot;align-items: center;&quot;&gt;
               &lt;img th:src=&quot;@{&#39;/uploads/&#39; + ${product.filename}}&quot; alt=&quot;product name&quot; width=&quot;150&quot; height=&quot;150&quot; /&gt;
                &lt;h2 th:text=&quot;${product.prodName}&quot;&gt;&lt;/h2&gt;
                &lt;p th:text=&quot;${product.prodDesc}&quot; /&gt;
                &lt;p th:text=&quot; &#39;₹ &#39;+ ${product.price}&quot; /&gt;
                &lt;p&gt;&lt;input type=&quot;button&quot; value=&quot;Add to Cart&quot; /&gt;&lt;/p&gt;
              &lt;/div&gt;

              &lt;br /&gt;
           &lt;/tr&gt; 
      &lt;/table&gt;
    &lt;/div&gt;
    
  &lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

I'm trying to show a list of product which is in the database in proper view as I told in the above line.

See the sample output: enter image description here
But I'm getting an only a single-column result.

答案1

得分: 1

.jobs {
  list-style: none;
}

.jobs li {
  float: left;
  margin-left: 20px;
  padding: 10px;
}

.jobs::after {
  content: "";
  display: grid;
  clear: both;
}
<ul class="jobs">
  <div th:each="product: ${products}">
    <li>
      <div class="card" style="align-items: center;">
        <img th:src="@{'/uploads/' + ${product.filename}}" alt="product name" width="150" height="150" />
        <h2 th:text="${product.prodName}"></h2>
        <p th:text="${product.prodDesc}" />
        <p th:text="'₹ ' + ${product.price}" />
        <p><input type="button" value="Add to Cart" /></p>
      </div>
    </li>
    <br>
  </div>
</ul>
英文:

I have tried solving this issue by adding CSS to the front end code.

    .jobs {
  list-style: none;
}

.jobs li {
  float: left;
  margin-left: 20px;
  padding: 10px;
  
}

.jobs::after {
  content: &quot;&quot;;
  display: grid;
  clear: both;
}




&lt;ul class=&quot;jobs&quot;&gt;
		&lt;div th:each=&quot;product: ${products}&quot;&gt;
			
			&lt;li&gt;
				&lt;div class=&quot;card&quot; style=&quot;align-items: center;&quot;&gt;
				 &lt;img th:src=&quot;@{&#39;/uploads/&#39; + ${product.filename}}&quot; alt=&quot;product name&quot; width=&quot;150&quot; height=&quot;150&quot; /&gt;
				  &lt;h2 th:text=&quot;${product.prodName}&quot;&gt;&lt;/h2&gt;
				  &lt;p th:text=&quot;${product.prodDesc}&quot; /&gt;
				  &lt;p th:text=&quot; &#39;₹ &#39;+ ${product.price}&quot; /&gt;
				  &lt;p&gt;&lt;input type=&quot;button&quot; value=&quot;Add to Cart&quot; /&gt;&lt;/p&gt; 
				&lt;/div&gt;
			&lt;/li&gt;
				&lt;br&gt;	
			
		&lt;/div&gt;
	&lt;/ul&gt;	

答案2

得分: 0

我认为你正在结合两种方法。你的输出有表行,但没有单元格,所以你可以使用<th>表示标题,使用<td>表示数据以水平方式分布数据。另一种方法是如果你想使用CSS网格布局 - 在这里查看

也许你可以先尝试只使用产品名称,直到你得到想要的格式,然后再添加其他元素。

英文:

I think you are combining two approaches. You have table rows for the output but no cells so you can use &lt;th&gt; for the header and &lt;td&gt; for the data to distribute the data horizontally. The other approach is if you want to use css grid - take a look here

Maybe just try with product name until you get the format you want, then add the other elements.

答案3

得分: 0

1) 将 commons-collections4 库添加到您的项目中。

例如,如果您使用的是 Maven,您可以在您的 pom.xml 中添加以下内容:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

这只是为了方便起见,当我们将列表分割成分区子列表时,可以节省一些额外的代码行。

2) 在您的控制器中,执行以下操作:

添加以下导入语句:

import org.apache.commons.collections4.ListUtils;

您可以使用此导入将产品列表转换为列表的列表:

ModelAndView model = new ModelAndView();
List<Product> products = pRepo.findAll();

// 将列表分割为所需的子列表:
int partitionSize = 3;
List<List<Product>> displayRows = ListUtils.partition(products, partitionSize);

// 使用这个新的列表的列表:
model.addObject("displayRows", displayRows);

model.setViewName("product");
return model;

现在,您有一个包含多个子列表的列表,每个子列表包含 3 个项目(或者在最后一个子列表中可能少于 3 个项目)。

每个子列表代表 HTML 表中的一行数据

3) 更改您的 Thymeleaf 模板

<div>
    <table>   
        <tr th:each="displayRow : ${displayRows}">
            <td th:each="product: ${displayRow}">

                <div class="card" style="align-items: center;">
                    <img th:src="@{'/uploads/' + ${product.filename}}" 
                         alt="product name" width="150" height="150" />
                    <h2 th:text="${product.prodName}"></h2>
                    <p th:text="${product.prodDesc}" />
                    <p th:text=" '&#8377; ' + ${product.price}" />
                    <p><input type="button" value="Add to Cart" /></p>
                </div>

            </td>
        </tr> 
    </table>
</div>

我们使用了两级迭代:第一级是对每个表格行进行迭代 - 每个子列表。第二级是对每个行中的项目进行迭代(表格单元格)。

需要注意的一点:在您的 Thymeleaf 模板中,您使用了这个:

<meta charset="ISO-8859-1">

我不建议这样做。我始终建议使用 UTF-8:

<meta charset="UTF-8">

然后,您还直接在模板中硬编码了卢比符号:。但由于这是嵌入在 HTML 中,您应该使用 HTML 显示序列(就像我在上面的代码中所做的):&amp;#8377;。但是,如果您在服务器上格式化了货币金额,您就不必使用这段代码 - 您将能够直接使用货币符号。

最终结果如下(请注意,我在我的测试设置中没有任何图片):

如何在Thymeleaf中水平获取数据库结果(每行4条记录)

您可以添加一些额外的 CSS 来改善卡片之间的间距。

英文:

You can make the following changes to your approach:

1) Add the commons-collections4 library to your project.

For example, if you are using Maven, you can add this to your pom.xml:

&lt;dependency&gt;
    &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;
    &lt;artifactId&gt;commons-collections4&lt;/artifactId&gt;
    &lt;version&gt;4.4&lt;/version&gt;
&lt;/dependency&gt;

This is just added as a convenience, to save us from writing some extra lines of code, when we split our list into partitioned sub-lists.

2) In your controller, do the following:

Add the following import:

import org.apache.commons.collections4.ListUtils;

You use this import to convert your list of products into a list of lists:

ModelAndView model = new ModelAndView();
List&lt;Product&gt; product= pRepo.findAll();

// Partition the list into the required sub-lists:
int partitionSize = 3;
List&lt;List&lt;Product&gt;&gt; displayRows = ListUtils.partition(products, partitionSize);

// use this new list of lists:
model.addObject(&quot;displayRows&quot;, displayRows);

model.setViewName(&quot;product&quot;);
return model;

Now, you have a list of sub-lists, where each sub-list contains 3 items (or maybe less than 3 in the final sub-list).

Each sub-list represents one row of data in your HTML table.

3) Change your Thymeleaf template

    &lt;div&gt;
        &lt;table&gt;   
            &lt;tr th:each=&quot;displayRow : ${displayRows}&quot;&gt;
                &lt;td th:each=&quot;product: ${displayRow}&quot;&gt;

                    &lt;div class=&quot;card&quot; style=&quot;align-items: center;&quot;&gt;
                        &lt;img th:src=&quot;@{&#39;/uploads/&#39; + ${product.filename}}&quot; 
                             alt=&quot;product name&quot; width=&quot;150&quot; height=&quot;150&quot; /&gt;
                        &lt;h2 th:text=&quot;${product.prodName}&quot;&gt;&lt;/h2&gt;
                        &lt;p th:text=&quot;${product.prodDesc}&quot; /&gt;
                        &lt;p th:text=&quot; &#39;&amp;#8377; &#39;+ ${product.price}&quot; /&gt;
                        &lt;p&gt;&lt;input type=&quot;button&quot; value=&quot;Add to Cart&quot; /&gt;&lt;/p&gt;
                    &lt;/div&gt;

                &lt;/td&gt;
            &lt;/tr&gt; 
        &lt;/table&gt;
    &lt;/div&gt;

We are using 2 levels of iteration: The first is for each table row - which is each sub-list. The second is for each item in the row (the table cells).

One point to note: In your Thymeleaf template you are using this:

&lt;meta charset=&quot;ISO-8859-1&quot;&gt;

I do not recommend this. I would always recommend using UTF-8:

&lt;meta charset=&quot;UTF-8&quot;&gt;

And, then you are also hard-coding the rupee symbol directly in your template: . But because this is embedded in HTML, you should use the HTML display sequence instead (like I do in the above code): &amp;#8377;. But if you formatted your currency amount on the server you would not have to use this code - you would be able to use the currency symbol directly.

The final result is as follows (note I do not have any pictures in my test set-up):

如何在Thymeleaf中水平获取数据库结果(每行4条记录)

You can add some more CSS to improve the spacing between cards.

huangapple
  • 本文由 发表于 2020年9月2日 23:11:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63708435.html
匿名

发表评论

匿名网友

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

确定