2017-02-10 20 views
0

控制器我可以使用具有多個值的Thymeleaf開關語句嗎?

@ControllerAdvice 
public class UserRoleAdvice { 

    private static final Logger log = LoggerFactory.getLogger(UserRoleAdvice.class); 

    @Autowired 
    UsersRepository usersRepository; 

    @ModelAttribute("currentRole") 
    public String currentRole(Principal principal, Model model) { 
     Users user = usersRepository.findOneByInitialName(principal.getName()); 
     if (user != null) { 
      log.info(user.getRole().toString()); 
      model.addAttribute("currentRole", user.getRole().toString()); 
      return user.getRole().toString(); 
     } else { 
      return "ANONYMOUS"; 
     } 
    } 
} 

我使用的是Thymeleaf switch語句來控制基於數據庫中的值我的網頁上顯示的內容。

<th:block th:unless="${currentROLE} eq 'EMPLOYEE'"> 
    <a href="/login" th:href="@{/login}" class="btn-login">Log In</a> 
</th:block> 

我想隱藏登錄頁面,如果${currentROLE}顯示了字符串員工或經理,但隨後表現出來,如果有對${currentROLE}沒有價值。

有沒有辦法做這樣的事情(僞代碼)?

<th:block th:unless="${currentROLE} eq 'EMPLOYEE' & || eq 'MANAGER'"> 
    <a href="/login" th:href="@{/login}" class="btn-login">Log In</a> 
</th:block> 

甚至

<th:block th:unless="${currentROLE} exists> 
    <a href="/login" th:href="@{/login}" class="btn-login">Log In</a> 
</th:block> 

回答

2

th:unless纔是正道。但你的支票是錯的,我想。試着用:

"${currentROLE.name == 'EMPLOYEE'}" 

和/或

"${currentROLE.name} == 'EMPLOYEE or MANAGER'" 

"${currentROLE.name} == 'EMPLOYEE' or ${currentROLE.name} == 'MANAGER'" 
+0

奇怪。第二個給我一個瘋狂的錯誤:「HTTP狀態500 - 請求處理失敗;嵌套的異常是org.thymeleaf.exceptions.TemplateInputException:模板解析期間發生錯誤(模板:「class path resource [templates/home.html]」)'' – santafebound

+0

@santafebound更新了答案。現在應該工作。 – Patrick

+1

謝謝。我用中間的一個,但他們都工作。 – santafebound

1

http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#switch-statements

有三種可能有些事情,你可能不希望,如果做一個/除非事情。這也不是開關;一個開關基本上是開關(大小寫,大小寫......)。這可以通過if語句來完成,但是除了幾個選項之外,開關更容易閱讀和擴展。

在這種情況下,它看起來更像

<div th:switch="${currentROLE.name}"> 
    <span th:case="EMPLOYEE">stuff</span> 
    <span th:case="MANAGER">other stuff</span> 
    <span th:case="*">default stuff</span> 
</div> 

「*」 表示默認情況下;如果沒有一個案例是真的,它就會去那裏。

如果唯一可能的值是EMPLOYEE,MANAGER或什麼也不是,那麼值得注意的是,如果沒有比較,任何非「false」,「off」或「no」的字符串都會計爲true。所以th:if = $ {currentROLE.name}將會發生,如果字符串存在並且在th時不爲null:除非= $ {currentROLE.name}發生,如果沒有值的話。這基本上就像JavaScript所做的那樣真實或虛假。

要考慮的事情是該程序將在未來如何發展以及您打算在此處做什麼。

+0

您有沒有使用單引號的原因?就像上面的''>'? – santafebound

+1

我學習Thymeleaf的方式和我使用的約定是用雙引號括住這些值的塊,並在內部使用單引號。只要保持一致,我認爲不重要,「經理」和「經理」實際上是相同的字符串。然而,「經理」和「經理」意味着不同的東西。 – Daveycakes

相關問題