2016-08-31 4 views
0

У меня есть страница, которая отображает список всех доступных журналов. Я хочу написать язык выражений тимелеафа, который выделяет уже подписанные журналы, используя там идентификатор журнала. Поэтому для всех подписанных журналов текст для гиперссылки href должен быть «Отменить подписку» и наоборот, если он не подписан.Springboot Thymeleaf: как форматировать строку в соответствии с условием

<!DOCTYPE html> 
    <html xmlns:th="http://www.thymeleaf.org"> 
    <head lang="en"> 

    <title>TBD</title> 

    <!--/*/ <th:block th:include="fragments/headinc :: head"></th:block> /*/--> 

    <link rel="stylesheet" 
     href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" /> 


    </head> 
    <body> 
     <div class="container"> 

      <h1 th:text="'Hello, ' + ${user.fullname} + '!'" /> 
      <p>Manage your subscriptions here</p> 

      <form role="form" id="form-search" class="form-inline" 
       th:action="@{/subscriptions}" method="get"> 
       <input type="text" class="form-control" id="filter" name="filter" 
        placeholder="Enter filter"></input> 
       <button type="submit" class="btn btn-default"> 
        <span class="glyphicon glyphicon-search"></span> Search 
       </button> 

       <a th:href="@{/logout}" class="btn btn-link" role="button">Logout</a> 
      </form> 
      <div th:if="${not #lists.isEmpty(journals)}"> 
       <form role="form" id="form-subscribe" th:action="@{/subscribe}" 
        method="post"> 
        <input type="hidden" name="journalId" id="journalId" /> 

       </form> 
       <table id="table" class="table"> 
        <thead> 
         <tr> 
          <th>Subject</th> 
          <th>Filename</th> 
          <th>Tags</th> 
          <th>View</th> 
          <th>Action</th> 
         </tr> 
        </thead> 
        <tbody> 
         <tr th:each="journal : ${journals}"> 
          <td th:text="${journal.subject}"><a 
           href="/product/${product.id}">Id</a></td> 
          <td th:text="${journal.filename}">Product Id</td> 
          <td th:text="${journal.tags}">Description</td> 
          <td><a>View</a></td> 
          <td><a id="href" 
           th:href="'javascript:subscribe(\'' + ${journal.id} + '\');'">Subscribe</a> 

          </td> 
         </tr> 
        </tbody> 

       </table> 
      </div> 
     </div> 
    </body> 
    <script type="text/javascript"> 
     function subscribe(journalId) { 
      $('#journalId').val(journalId); 
      $('#form-subscribe').submit(); 

     } 
    </script> 


    <script type="text/javascript" th:inline="javascript"> 
     /*<![CDATA[*/ 

     $(document).ready(function() { 
      var modelAttributeValue = [[${subscriptions}]]; 
      console.log(modelAttributeValue); 
      alert(modelAttributeValue); 

      var array = modelAttributeValue.split(';'); 
      console.log(array); 
      alert(array); 
     }); 

     /*]]>*/ 
    </script> 
    </html> 

Контроллер

@Controller 
    public class SubscriptionController { 

     @Autowired 
     private SubscriberService subscriberService; 

     @RequestMapping(value = "/subscribe", method = RequestMethod.POST) 
     String subscribe(Model model, @RequestParam("journalId") Integer journalId) { 

      JournalToken token = (JournalToken) SecurityContextHolder.getContext().getAuthentication(); 
      Account user = (Account) token.getCredentials(); 
      model.addAttribute("user", user); 

      Journal journal = this.subscriberService.findJournalById(journalId); 

      this.subscriberService.subscribeJournalForSubscriber(journal, user); 

      return "redirect:subscriptions"; 
     } 

     @RequestMapping(value = "/subscriptions", method = RequestMethod.GET) 
     String list(Model model) { 

      JournalToken token = (JournalToken) SecurityContextHolder.getContext().getAuthentication(); 
      Account user = (Account) token.getCredentials(); 
      model.addAttribute("user", user); 

      ArrayList<Journal> journals = this.subscriberService.FindAllJournals(); 

      model.addAttribute("journals", journals); 

      StringBuilder sub = new StringBuilder(); 
      ArrayList<Subscription> subscribed = this.subscriberService.getSubscribedJournalsForSubscriber(user); 

      model.addAttribute("subscriptions", subscribed); 

      return "subscriptions"; 
     } 
    } 

модель подписки

@Entity 
    @Table(uniqueConstraints={@UniqueConstraint(columnNames={"userId", "journalId"})}) 
    public class Subscription { 

     @Id 
     @GeneratedValue(strategy = GenerationType.AUTO) 
     private Integer id; 

     @Version 
     private Integer version; 

     private Integer userId; 
     private Integer journalId; 

     public void setId(Integer id) { 
      this.id = id; 
     } 

     public Integer getId() { 
      return this.id; 
     } 

     public void setVersion(Integer version) { 
      this.version = version; 
     } 

     public Integer getVersion() { 
      return this.version; 
     } 

     public void setUserId(Integer userId) { 
      this.userId = userId; 
     } 

     public Integer getUserId() { 
      return this.userId; 
     } 

     public void setJournalId(Integer journalId) { 
      this.journalId = journalId; 
     } 

     public Integer getJournalId() { 
      return this.journalId; 
     } 
    } 

ответ

1

вы можете изменить ваш ArrayList подписался иметь только идентификаторы журналов (более оптимизировано). Так, в контроллере вы можете иметь что-то вроде этого

ArrayList<Integer> subscribed = 
this.subscriberService.getSubscribedJournalsForSubscriber(user); //modify it so it returns the journals ids instead of the whole object(Subscription) 

затем в thymeleaf изменить якорь с чем-то вроде этого

<a id="href" th:href="'javascript:subscribe(\'' + ${journal.id} + '\');'"> 
    <span th:if="${#lists.contains(subscriptions, journal.id) }" th:text="Unsubscribe"> Unsubscribe </span> 
    <span th:if="not ${#lists.contains(subscriptions, journal.id) }" th:text="Subscribe"> Subscribe </span> 
</a> 

Посмотрите документацию thymeleaf http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html

/* 
* Check if element or elements are contained in list 
*/ 
${#lists.contains(list, element)} 
${#lists.containsAll(list, elements)} 
Смежные вопросы