Home > Net >  Is it possible to use Spring model in Javascript functions inside Thymeleaf template?
Is it possible to use Spring model in Javascript functions inside Thymeleaf template?

Time:11-27

I've the following domain:

@Document(collection = "backupareas")
public class BackupArea {
    @Id
    private String id;

    private String area;

    private List<Tape> tapes;

In my template I would that when I change area a js function fill the tape select with related area tapes.

<div class="form-group col-md-3">
   <label for="backup"><i>*</i> Backup</label>
   <select id="backup" class="form-control" name="backup" required onchange="loadTapes();">
       <option value="" selected="selected">--- Select Area ---</option>
       <option th:each="area: ${areas}" th:value="${area.getArea()}" th:text="${area.getArea()}"></option>
    </select>
</div>

<div class="form-group col-md-3">
    <label for="tape"><i>*</i> Tape</label>
    <select id="tape" class="form-control" name="tape" required >

    </select>

I start with this js function, but I don't know how to use (or if it is possible) model variables.

function loadTapes() {
       var area = $("#backup").val();
       console.log($("#backup").index(area));

      if($("#backup").index(area) == 1) {
              $("#tape").empty();
              return false;
      }
      $("#tape").empty();

      var select = $('#tape');
      select.append($("<option />").val("").text("--- Select one ---"));
      // Here should use model variable to loop over tapes related to the selected area
      select.append($("<option/>").val(TAPE).text(TAPE));
            
  }
 

CodePudding user response:

I solved. I created a fragment as:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<th:block th:fragment="tapes">
    <th:block th:if="${tapes != null}">
            <option th:each="tape: ${tapes}" th:value="${tape}" th:text="${tape}"></option>
    </th:block>
</th:block>
</body>
</html>

In the main template I call an ajax method:

function loadTapes() {
                     
      $("#tape").empty();
      $.post("/area/loadTapes", {area: area}, function (data) {
      $('#tape').append(data);
          });
}

The loadTapes method is:

PostMapping("/area/loadTapes")
    public String loadTape(@RequestParam("area") String area, Model model) {
        BackupArea backupArea = backupAreaService.findByArea(area);
        List<Integer> tapes = new ArrayList<>();
        for(Tape tape: backupArea.getTapes()) {
            tapes.add(tape.getTape());
        }
        
        model.addAttribute("list", tapes);
        return "/backup/tapes :: list";
    }
  • Related