ヒューゴサイトにランダムなページボタンを追加


私は、それがXKCDにどれくらい便利であるかを思い出した後に、私のHugoサイトの1つにランダムボタンを加えたかったです.それは単にあなたのランダムな記事を選択するために、単純なスクリプトを書いて、JSONファイルを生成する必要がありますHugoで本当に簡単なプロセスだと判明します.

何を作っているのですか。



ハウツー


ページの作成


Hugoは便利にJSONデータを出力させるので、残りの静的ファイルと一緒に展開されるルートで1つを作成します.この例のカップル警告
  • 私のフィルタは単純なので、サイトは1ページのアーキタイプを持っています.あなたは間違いなくヒューゴのwhereother functionsでMroe創造を得ることができます.
  • サイト検索のためのこのインデックスは、私が使っていたテーマに既にありました.あなただけのランダマイザをしたい場合は、tagscontentsのようなすべての余分なデータフィールドを削除することができます.
  •    # layouts/_default/index.json
    
       {{- $.Scratch.Add "index" slice -}}
       {{- range where site.RegularPages "Type" "in" site.Params.mainSections -}}
       {{ $date:= .PublishDate.Format "02"}}
       {{- $.Scratch.Add "index" (dict "title" .Title "date" $date "tags" .Params.tags "image" .Params.image "categories" .Params.categories "contents" .Plain "permalink" .Permalink) -}}
       {{- end -}}
       {{- $.Scratch.Get "index" | jsonify -}}
    
    私はconfig.tomlに小さなパームを追加する必要がありました.
    [outputs]
        home = ["json", "html"]
    

    あなたが少し深く潜りたいならば、記事 PROD JSON出力


    参照のために、上記のhugoコードが出力を終えるJSON.
    [
       {
         "categories": [
           "Developers"
         ],
         "contents": "text of the document",
         "date": "07",
         "image": "images/post/article-1.png",
         "permalink": "https://permalink",
         "tags": [
            "Software Development"
         ],
         "title": "Title of the most recent article"
       },
     ...
     ]
    

    2 . HTMLページでJSONを使う


    HTMLページにこのようなものを追加できます.私は、ボタンがページに表示されるpartialでこれを持っています.
        <script>
         var searchIndexData = [];
         // fetch on page load from the search index
         let json_path = window.location.origin + '/index.json'
    
         fetch(json_path).then(function (response) {
            return response.json();
         })
         .then(function (data) {
            searchIndexData = data;
         })
         .catch(function (err) {
            console.log(err)
         });
    
    
         function sendToRandomArticle() {
         let randIndex = Math.floor(Math.random() * searchIndexData.length);
         let randArticle = searchIndexData[randIndex]['permalink'] + '?utm_source=RandomButton';
         window.location.href = randArticle;
         }
    
        </script>
        ...
        ...
        <button type="button" class="btn btn-primary" onclick='sendToRandomArticle()'>Random</button>
    
    それだ!それは簡単だった.