如何在Jekyll标签插件中检测当前页面?

时间:2011-09-20 00:06:16

标签: jekyll liquid

我有一个Jekyll(Liquid)块插件,我想检测当前页面是什么。我看到上下文被传递到render中,我可以将当​​前站点对象检索为context.registers [:site]。但是,尝试将当前页面作为context.registers [:page]失败。

我想解决的问题是创建一个简单的块插件来检测当前页面是否是标签中提到的页面,然后突出显示它。

任何提示都将不胜感激。

谢谢!

4 个答案:

答案 0 :(得分:16)

原来我们也可以这样做:

  def render(context)
    page_url = context.environments.first["page"]["url"]

哪个不明显,但不需要修补代码。

答案 1 :(得分:2)

context['page']似乎返回包含当前页面大部分属性的哈希值,包括urlpath

因此可以使用

检索实际的页面对象
context.registers[:site].pages.detect { |p| p.path==context['page']['path'] }

答案 2 :(得分:1)

我认为现在用Jekyll做到这一点并不是一个好方法。 convertible.rb仅将site对象传递给Liquid,后者不包含任何特定于页面的数据。

我建议您只需编辑convertible.rb即可传递所需的数据,向主项目提交拉取请求以提取更改,并在本地使用fork生成您的网站。万岁开源!

以下简单的补丁在本地针对Jekyll 0.11.0工作,使得在Liquid中的页面哈希可用context.registers[:page](注意:此时它是预先转换的哈希,因此您可以访问{{ 1}},而不是context.registers[:page]['url']):

context.registers[:page].url

希望有所帮助!

答案 3 :(得分:1)

在制作需要稍微不同地显示当前页面的菜单时,总会出现这个问题。这是我为 Bootstrap 5 编写的 Jekyll 插件:

# Copyright 2020 Michael Slinn
#
# Apache 2 License
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.

module Jekyll
  # Generates a Bootstrap 5 nav item.
  # 
  # Usage: {% nav_item icon link text %}
  #   Quotes are not used
  #   icon is assumed to be within the /assets/icons directory
  #   link must reference a local web page, do not preface with http: or https:
  #   text can be one or more words
  # 
  # Example:           
  # {% nav_item house-door.svg /index.html Welcome! %}

  class Bootstrap5NavItem < Liquid::Tag

    def initialize(href, command_line, tokens)
      super

      @active = '"'

      tokens = command_line.strip.split(" ")

      @icon = tokens.shift
      @link = tokens.shift
      @text = tokens.join(" ").strip
    end

    def render(context)
      relative_link = @link.delete_prefix('/')
      page = context['page']['path']  # relative to site root
      #puts "******* page=#{page}; @link=#{@link}"

      if page == relative_link then
        %Q(<li>
          <a class="nav-link active" aria-current="page" href="#">
            <img class="feather" src="/assets/icons/#{@icon}">
            #{@text}
          </a>
        </li>)
      else
        %Q(<li>
          <a class="nav-link" href="#{@link}">
            <img class="feather" src="/assets/icons/#{@icon}">
            #{@text}
          </a>
        </li>)
      end
    end
  end
end

Liquid::Template.register_tag('nav_item', Jekyll::Bootstrap5NavItem)