1

h2各見出しの後に TOC への参照を追加するフィルターを作成しようとしています。

これが私がやったことですが、うまくいきません。コードを変更するたびに、関連するすべてのページが再コンパイルされません。

{プロジェクト ディレクトリ}/ルール:

compile '/**/*.md' do
  filter :kramdown
  layout '/default.*'
  filter :add_ref_to_toc
  filter :add_toc_french
  write item.identifier.without_ext + '/index.html'
end

{プロジェクト ディレクトリ}/lib/filters/add_ref_to_toc.rb:

require 'nokogiri'
class AddRefToTocFilter < Nanoc::Filter

  identifier :add_ref_to_toc

  def run(content, params={})    
    doc = Nokogiri::HTML.fragment(content)
    doc.css('#contents h2') do |header|
      header.add_next_sibling "<br/><a href='#toccontent'>Aller à la table des matières</a><br/><br/>"
    end
    doc.to_s
  end

end

処理後のページ:

<div id="contents">
<h2>title 1</h2>
<br/><a href='#toccontent'>Aller à la table des matières</a><br/><br/>

<h2>title 2</h2>
<br/><a href='#toccontent'>Aller à la table des matières</a><br/><br/>

<h2>title 3</h2>
<br/><a href='#toccontent'>Aller à la table des matières</a><br/><br/>
</div>
4

1 に答える 1

0

これが機能するコードです。

require 'nokogiri'
class AddRefToTocFilter < Nanoc::Filter

  identifier :add_ref_to_toc

  def run(content, params={})    
    doc = Nokogiri::HTML(content)
    headers = doc.css('#contents h2')
    headers.each do |header|
      header.add_next_sibling(Nokogiri::HTML.fragment("<br/><a href='#toccontent'>&#124;Aller à la table des matières&#124;</a><br/><br/>"))
    end
    doc.to_s
  end

end
于 2019-11-12T09:16:37.503 に答える