2017-02-10 19 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

相关问题