developer tip

Jekyll-메뉴 모음에서 현재 탭을 자동으로 강조 표시

optionbox 2020. 10. 18. 09:22
반응형

Jekyll-메뉴 모음에서 현재 탭을 자동으로 강조 표시


github를 사용하여 정적 사이트를 호스팅하고 Jekyll을 사용하여 생성합니다.

메뉴 모음 ( <ul>)이 있고 <li>현재 페이지에 해당하는 CSS 강조 표시를 위해 다른 클래스를 할당하고 싶습니다 .

따라서 의사 코드와 같습니다.

<li class={(hrefpage==currentpage)?"highlight":"nothighlight"} ...>

또는 <ul>Jekyll 에서 전체 생성 할 수도 있습니다.

위반 사항이 아닌 최소한의 변경으로 어떻게이 작업을 수행 할 수 <ul>있습니까?


예, 할 수 있습니다.
이를 위해 우리는 현재 페이지가 항상 page템플릿에서 liquid 변수로 표현된다는 사실 과 각 게시물 / 페이지의 page.url속성에 고유 한 식별자가 있다는 사실을 활용 합니다.

이것은 우리가 탐색 페이지를 구축하기 위해 루프를 사용해야 함을 의미하며, 그렇게함으로써 page.url루프의 모든 멤버에 대해 확인할 수 있습니다 . 일치하는 항목을 찾으면 해당 요소를 강조 표시합니다. 여기 있습니다 :

  {% for node in site.pages %}
    {% if page.url == node.url %}
      <li class="active"><a href="{{node.url}}" class="active">{{node.title}}</a></li>
    {% else %}
      <li><a href="{{node.url}}">{{node.title}}</a></li>
    {% endif %}
  {% endfor %}

이것은 예상대로 작동합니다. 그러나 탐색 모음에 모든 페이지가 포함되는 것을 원하지는 않을 것입니다. 페이지 "그룹화"를 에뮬레이트하려면 다음과 같이 할 수 있습니다.

## Put the following code in a file in the _includes folder at: ./_includes/pages_list

{% for node in pages_list %}
  {% if group == null or group == node.group %}
    {% if page.url == node.url %}
      <li class="active"><a href="{{node.url}}" class="active">{{node.title}}</a></li>
    {% else %}
      <li><a href="{{node.url}}">{{node.title}}</a></li>
    {% endif %}
  {% endif %}
{% endfor %}
{% assign pages_list = nil %}
{% assign group = nil %}

이제 페이지를 "그룹화"할 수 있습니다. 페이지에 그룹을 제공하려면 YAML Front Matter 페이지에서 지정해야합니다.

---
title: blah
categories: blah
group: "navigation"
---    

마지막으로 새 코드를 사용할 수 있습니다! 템플릿에서 탐색이 필요할 때마다 포함 파일을 "호출"하고 표시 할 일부 페이지와 그룹을 전달하면됩니다.

<ul>
  {% assign pages_list = site.pages %}
  {% assign group = 'navigation' %}
  {% include pages_list %}
</ul>

이 기능은 Jekyll-Bootstrap 프레임 워크 의 일부입니다 . http://jekyllbootstrap.com/api/bootstrap-api.html#jbpages_list에서 설명 된 코드에 대한 정확한 문서를 볼 수 있습니다.

마지막으로 웹 사이트 자체에서 작동하는 모습을 볼 수 있습니다. 오른쪽 탐색을 보면 현재 페이지가 녹색으로 강조 표시된 것을 볼 수 있습니다. 강조 표시된 탐색 링크의 예


가장 간단한 탐색 요구 사항은 나열된 솔루션이 지나치게 복잡하다고 생각합니다. 다음은 전면 문제, 자바 스크립트, 루프 등을 포함하지 않는 솔루션입니다.

페이지 URL에 액세스 할 수 있으므로 다음과 같이 URL을 정규화 및 분할하고 세그먼트에 대해 테스트 할 수 있습니다.

{% assign current = page.url | downcase | split: '/' %}

<nav>
  <ul>
    <li><a href='/about' {% if current[1] == 'about' %}class='current'{% endif %}>about</a></li>
    <li><a href='/blog' {% if current[1] == 'blog' %}class='current'{% endif %}>blog</a></li>
    <li><a href='/contact' {% if current[1] == 'contact' %}class='current'{% endif %}>contact</a></li>
  </ul>
</nav>

물론 이것은 정적 세그먼트가 탐색을 설명하는 수단을 제공하는 경우에만 유용합니다. 더 복잡한 것은 @RobertKenny가 시연 한 것과 같은 머리말을 사용해야합니다.


@ ben-foster의 솔루션과 유사하지만 jQuery를 사용하지 않습니다.

저는 간단한 것이 필요했습니다. 이것이 제가 한 일입니다.

내 머리말에 나는 active

예 :

---
layout: generic
title:  About
active: about
---

다음 섹션에 탐색이 포함되어 있습니다.

    <ul class="nav navbar-nav">
        {% if page.active == "home" %}
            <li class="active"><a href="#">Home</a></li>
        {% else %}
            <li><a href="/">Home</a></li>
        {% endif %}
        {% if page.active == "blog" %}
            <li class="active"><a href="#">Blog</a></li>
        {% else %}
            <li><a href="../blog/">Blog</a></li>
        {% endif %}
        {% if page.active == "about" %}
            <li class="active"><a href="#">About</a></li>
        {% else %}
            <li><a href="../about">About</a></li>
        {% endif %}
    </ul>

내비게이션의 링크 수가 매우 좁기 때문에 이것은 나를 위해 작동합니다.


다음은 현재 페이지를 강조하는 가장 좋은 방법이라고 생각하는 내 솔루션입니다.

다음 과 같이 _config.yml탐색 목록정의하십시오 .

navigation:
  - title: blog
    url: /blog/
  - title: about
    url: /about/
  - title: projects
    url: /projects/

그런 다음 _includes / header.html 파일에서 목록을 반복하여 현재 페이지 ( page.url )가 탐색 목록의 항목과 유사한 지 확인해야합니다. 그렇다면 활성 클래스를 설정하고 <a>태그에 추가하면됩니다 .

<nav>
  {% for item in site.navigation %}
      {% assign class = nil %}
      {% if page.url contains item.url %}
          {% assign class = 'active' %}
      {% endif %}
      <a href="{{ item.url }}" class="{{ class }}">
          {{ item.title }}
      </a>
  {% endfor %}
</nav>

그리고 equals = 연산자 대신 contains 연산자를 사용하기 때문에 '/ blog / post-name /' 또는 'projects / project-name / ' 과 같은 URL에서 작동하도록 추가 코드를 작성할 필요가 없습니다. ' . 그래서 정말 잘 작동합니다.

추신 : 페이지에 영구 링크 변수 를 설정하는 것을 잊지 마십시오 .


이를 위해 약간의 JavaScript를 사용했습니다. 메뉴에 다음 구조가 있습니다.

<ul id="navlist">
  <li><a id="index" href="index.html">Index</a></li>
  <li><a href="about.html">About</a></li>
  <li><a href="projects.html">Projects</a></li>
  <li><a href="videos.html">Videos</a></li>
</ul>

이 자바 스크립트 스 니펫은 현재 해당 페이지를 강조합니다.

$(document).ready(function() {
    var pathname = window.location.pathname;

    $("#navlist a").each(function(index) {
        if (pathname.toUpperCase().indexOf($(this).text().toUpperCase()) != -1)
            $(this).addClass("current");
    });

    if ($("a.current").length == 0)
        $("a#index").addClass("current");
});

내 접근 방식은 페이지의 YAML 서문에 사용자 지정 변수를 정의하고이를 <body>요소 에 출력하는 것입니다 .

<body{% if page.id %} data-current-page="{{ page.id }}"{% endif %}> 

내 탐색 링크에는 링크 된 페이지의 식별자가 포함됩니다.

<nav>
    <ul>
        <li><a href="artists.html" data-page-id="artists">artists</a></li>
        <li><a href="#" data-page-id="contact">contact</a></li>
        <li><a href="#" data-page-id="about">about</a></li>
    </ul>
</nav>

페이지 서문에서 페이지 ID를 설정합니다.

---
layout: default
title: Our artists
id: artists
---

마지막으로 활성 링크를 설정하는 약간의 jQuery :

// highlight current page
var currentPage = $("body").data("current-page");
if (currentPage) {
    $("a[data-page-id='" + currentPage + "']").addClass("active");
}

여기에 많은 혼란스러운 대답이 있습니다. 나는 단순히 다음을 사용합니다 if.

{% if page.name == 'limbo-anim.md' %}active{% endif %} 

페이지를 직접 참조하여 원하는 클래스에 넣습니다.

<li><a class="pr-1 {% if page.name == 'limbo-anim.md' %}activo{% endif %} " href="limbo-anim.html">Animación</a></li>

끝난. 빨리.


나는 page.path파일 이름을 사용 하고 제거했습니다.

<a href="/" class="{% if page.path == 'index.html' %}active{% endif %}">home</a>

많은 좋은 답변이 이미 있습니다.

이 시도.

위의 답변을 약간 변경합니다.

_data/navigation.yaml

- name: Home
  url: /
  active: home
- name: Portfolio
  url: /portfolio/
  active: portfolio
- name: Blog
  url: /blog/
  active: blog

페이지에서-> portfolio.html(상대적인 활성 페이지 이름을 가진 모든 페이지에 대해 동일)

---
layout: default
title: Portfolio
permalink: /portfolio/
active: portfolio
---

<div>
  <h2>Portfolio</h2>
</div>

Navigation html part

<ul class="main-menu">
  {% for item in site.data.navigation %}
    <li class="main-menu-item">
      {% if {{page.active}} == {{item.active}} %}
        <a class="main-menu-link active" href="{{ item.url }}">{{ item.name }}</a>
      {% else %}
        <a class="main-menu-link" href="{{ item.url }}">{{ item.name }}</a>
      {% endif %}
    </li>
  {% endfor %}
</ul>

The navigation of your website should be an unordered list. To get the list items to lighten up when they are active, the following liquid script adds an 'active' class to them. This class should be styled with CSS. To detect which link is active, the script uses ‘contains’, as you can see in the code below.

<ul>
  <li {% if page.url contains '/getting-started' %}class="active"{% endif %}>
    <a href="/getting-started/">Getting started</a>
  </li>
  ...
  ...
  ...
</ul>

This code is compatible with all permalink styles in Jekyll. The ‘contains’ statement succesfully highlights the first menu item at the following URL’s:

  • getting-started/
  • getting-started.html
  • getting-started/index.html
  • getting-started/subpage/
  • getting-started/subpage.html

Source: http://jekyllcodex.org/without-plugin/simple-menu/


Here is a jQuery method to do the same

  var pathname = window.location.pathname;

  $(".menu.right a").each(function(index) {
    if (pathname === $(this).attr('href') ) {
      $(this).addClass("active");
    }
  });

참고URL : https://stackoverflow.com/questions/8340170/jekyll-automatically-highlight-current-tab-in-menu-bar

반응형