Springboot Thymeleaf:如何根据条件格式化行

时间:2016-08-31 06:46:01

标签: spring-boot thymeleaf

我有一个页面显示所有可用期刊的列表。我想写一个百里香表达语言,突出显示已经订阅的期刊使用期刊ID。因此,对于所有订阅的期刊,超链接href的文本应为"取消订阅"反之,如果没有订阅。

  <!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 个答案:

答案 0 :(得分:1)

您可以更改您订阅的arrayList只包含日志的ID(更优化)。 所以,在控制器中你可以有这样的东西

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

然后在百里香叶中用这样的东西改变锚点

<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>

查看百里香[{3}}

的文档
/*
 * Check if element or elements are contained in list
 */
${#lists.contains(list, element)}
${#lists.containsAll(list, elements)}