带有自己的控制器的 Thymeleaf 片段 [英] Thymeleaf fragment with own controller

查看:16
本文介绍了带有自己的控制器的 Thymeleaf 片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 thymeleaf 创建一个片段,它有自己的控制器,所以只要我包含片段,控制器就会被调用并填充必要的模型属性.对我来说,这听起来像是一个基本要求,但我是 thymeleaf 的新手,无法弄清楚.例如,我有一个这样的片段:

<tr th:each="prod : ${prods}"><td th:text="${prod.name}"/></tr>

除了这个片段,我还有一个看起来像这样的控制器:

@RequestMapping(value="/getProducts")公共模型产品(模型模型){列表<字符串>产品 = getProductList();model.addAttribute("prods", 产品)退货模式;}

那么我怎样才能绑定这两个呢?我正在使用 spring-boot 并且我没有更改或编辑任何解析器.谢谢,同行

解决方案

von Spring MVC 和一个模型的想法是,在视图中只渲染数据.因此,从模板中的任何位置调用服务或控制器都是一个坏主意.

你可以用一个函数addDataForTableFragment(Model model)来解决这个问题.这必须从使用带有片段的模板的控制器调用.如果您需要多种方法的数据,请查看 "ModelAttribute".

I want to create a fragment with thymeleaf that has its own controller, so anytime I include the fragment, the controller is called and fills the necessary model attributes. To me this sounds like a basic request but I am new to thymeleaf and can't figure it out. So for example I have a fragment like this:

<div th:fragment="table">
  <tr th:each="prod : ${prods}">
    <td th:text="${prod.name}"/>
  </tr>
</div>

In addition to this fragment, I would have a controller that looks somewhat like this:

@RequestMapping(value="/getProducts")
public Model products(Model model){
    List<String> products = getProductList();
    model.addAttribute("prods", products)
    return model;
}

So how can I bind those two? I am using spring-boot and I did not change or edit any resolver. Thanks, Peer

解决方案

The idea von Spring MVC and a model is, that in the view only data a rendered. So it's a bad idea to call a service or a controller from any place in a template.

You can solve this problem with a function addDataForTableFragment(Model model). This must be called from your controller which uses the template with the fragment. If you need the data at many method have a look a "ModelAttribute".

这篇关于带有自己的控制器的 Thymeleaf 片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆