Показать список в index.html с Thymeleaf - PullRequest
0 голосов
/ 18 февраля 2019

Я использую SpringBoot y Thymeleaf.

Как мне сделать, чтобы отобразить список продуктов в index.html в момент загрузки страницы?

В настоящее время products.html показываетвсе продукты из bd и index.html показывают фрагмент с заголовком вида products.html, но я не знаю, как сделать, чтобы отобразить продукты.

, если я ошибаюсь с моим подходомКак правильно это сделать?

index.html

<body>
<section layout:fragment="custom-content">
    <br> <br>
    <div class="container">
        <section th:replace="products :: content"></section>
                <br> <br>
        <h2>This is index.html</h2>
        </div>

это index.html с фрагментом products.html index.html

products.html

<body>
<div class="container">
    <div th:fragment="content">

        <h3>This is the fragment from products.html</h3>

        <h2>List of products</h2>
        <table class="table table-stripped">
            <tr>
                <th>Id</th>
                <th>Description</th>
                <th>Price</th>
                <th>Image Url</th>
                <th>List</th>
                <th>Edit</th>
                <th>Delete</th>
            </tr>

            <tr th:each="product : ${products}">
                <td th:text="${product.id}"></td>
                <td th:text="${product.description}"></td>
                <td th:text="${product.price}"></td>
                <td th:text="${product.imageUrl}"></td>
                <td><a th:href="${'/products/numArt/' + product.numArt}">View</a></td>
                <td><a>Edit</a></td>
                <td><a>Delete</a></td>
            </tr>
        </table>

        <div class="row">
            <div class="col-sm-3">
                <button>New Product</button>
            </div>
        </div>

    </div>
</div>

это products.html products.html

контроллер

@GetMapping("/products")
public String listProducts(Model model) {
    System.out.println("Get all products...");
    model.addAttribute("products", productRepository.findAll());
     return "products";
    }

1 Ответ

0 голосов
/ 19 февраля 2019

Вы связываете products объект в вашем products.html не с фрагментами.Поэтому создайте другой метод, подобный приведенному ниже.

@GetMapping("/products/fragment")
public ModelAndView listOfProducts() {
     ModelAndView mv = new ModelAndView("index::custom-content");
    mv.addObject("products", productRepository.findAll());
     return mv;
    }

и вызовите его с помощью ajax из вашего index.html.добавьте следующие строки в ваш индексный файл

<script th:inline="javascript">
    $(document).ready(function () {
		   loadData();
       });
       
     function loadData(){
     $.ajax({
			  type: 'get',
			  url: /*[[ @{'/product/fragment'} ]]*/,
			  
			  success: function(data){
				 $('.container').html(data);
				},
			  async:false
			})
     
     
     }
     </script>
<body>
<section >
    <br> <br>
    
    
    <div class="container">
    <div th:fragment="custom-content">
        <section th:replace="products :: content"></section>
                <br> <br>
        <h2>This is index.html</h2>
    </div>
    </div>
    </section>....

надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...