【问题标题】:Bootstrap Navbar Highlighting in Thymeleaf's layoutThymeleaf 布局中的 Bootstrap 导航栏突出显示
【发布时间】:2016-01-10 06:03:53
【问题描述】:

我正在评估 spring boot + MVC + bootstrap 。我面临的一个问题是 thymeleaf 中引导程序的导航栏突出显示问题。

希望 thymeleaf 能判断出应该高亮的tab。

我搜索并找到了这个解决方案:Bootstrap Navbar Highlighting in Thymeleaf

在包含(外部)页面中,它使用

<div th:replace="header::header('home')">
  to be replaced header
</div>

指定home 选项卡应突出显示。

在包含的(内部)页面中,它使用

<nav class="..." th:fragment="header(activeTab)">
<ul class="nav navbar-nav">
  <li th:class="${activeTab == 'home'} ? 'active' : null "><a href="#" th:href="@{/home}">Home</a></li>
</ul>

判断这个标签是否高亮。

它适用于每一页但不适用于布局

在布局页面中,包含(外部)页面是一个装饰器,用于装饰其他页面(主页/关于/联系...)。选项卡值在此处待定。

例如

<div th:replace="header::header('home')">
  to be replaced header
</div>
<div layout:fragment="content">
  layout
</div>
<div th:replace="footer::footer">
  to be replaced footer
</div>

我无法在布局文件中预先分配home 选项卡。 有什么办法解决吗?

可以通过控制器甚至控制器的方法来判断吗?

环境:

springboot.version 1.3.0.M5
spring.version :4.2.1.RELEASE 

非常感谢!

【问题讨论】:

    标签: spring twitter-bootstrap spring-mvc spring-boot thymeleaf


    【解决方案1】:

    更改此行&lt;nav class="..." th:fragment="header(activeTab)"&gt; 对此 &lt;nav class="..." th:fragment="header(activeTab='activeTab')"&gt; 它对我有用

    【讨论】:

      【解决方案2】:

      这不是您问题的确切解决方案,但也许您会喜欢这个想法。您可以使用请求上下文路径来识别实际选择了哪个选项卡,因此您可以使用${#httpServletRequest.getContextPath()},然后可能是这样的:

      <ul class="nav navbar-nav" th:with="view=${#httpServletRequest.getServletPath()}">
        <li th:classappend="${#strings.startsWith(view,'/home')? 'active' : ''}"><a href="#" th:href="@{/home}">Home</a></li>
      </ul>
      

      或者你可以使用 ControllerAdvice:

      @ControllerAdvice(assignableTypes = { MyController.class })
      public class MyControllerAdvice {
      
        @ModelAttribute
        public void addAttributes(@RequestParam Map<String, String> params, Model model, HttpServletRequest request) {
      String activeTab = ... whatever
          model.addAttribute("active_tab", activeTab);
        }
      }
      

      使用@ControllerAdvice 有一个很大的缺点。如果您打算使用 Spring WebFlow 来创建多页表单(向导),那么它将无法工作,因为 WebFlow 不使用模型属性。

      【讨论】:

      • 谢谢,应该是th:with="path=${#httpServletRequest.getServletPath()}"。是否可以通过控制器来判断?
      • 是的,你可以,你可以创建@ControllerAdvice并添加属性active_tab
      猜你喜欢
      • 2019-08-19
      • 1970-01-01
      • 2020-06-03
      • 2018-01-10
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      相关资源
      最近更新 更多