Browse Source

posts widget: Add filter to exclude tags (Close #170)

* Change `tags` option to `tags_include`
* Add `tags_exclude` option
George Cushen 7 years ago
parent
commit
80e833c5e9
2 changed files with 31 additions and 10 deletions
  1. 5 2
      exampleSite/content/home/posts.md
  2. 26 8
      layouts/partials/widgets/posts.html

+ 5 - 2
exampleSite/content/home/posts.md

@@ -12,8 +12,11 @@ widget = "posts"
 # Order that this section will appear in.
 weight = 40
 
-# Show posts that contain the following tags. Default to any tags.
-tags = []
+# Filter posts by tag.
+#  By default, show all recent posts.
+#  Filtering example: `tags_include = ["hugo", "academic"]`
+tags_include = []
+tags_exclude = []
 
 # Number of posts to list.
 count = 5

+ 26 - 8
layouts/partials/widgets/posts.html

@@ -22,16 +22,34 @@
 
     {{ with $page.Content }}<p>{{ . | markdownify }}</p>{{ end }}
 
-    {{ if $page.Params.tags }}
-      {{ range first $page.Params.count (where (where (where $.Data.Pages "Type" "post") ".Params.tags" "intersect" $page.Params.tags) ".Params.notonhomepage" nil) }}
-        {{ $params := dict "post" . "page" $page }}
-        {{ partial "post_li" $params }}
-      {{ end }}
-    {{ else }}
-      {{ range first $page.Params.count (where (where $.Data.Pages "Type" "post") ".Params.notonhomepage" nil) }}
+    {{ $posts := where (where $.Data.Pages "Type" "post") ".Params.notonhomepage" nil }}
+    {{ if $page.Params.tags_include }}
+      {{ $posts := where (where (where $.Data.Pages "Type" "post") ".Params.tags" "intersect" $page.Params.tags_include) ".Params.notonhomepage" nil }}
+    {{ end }}
+
+    {{ $.Scratch.Add "show_post" "1" }}
+    {{ range $post := first $page.Params.count $posts }}
+
+      {{ $.Scratch.Set "show_post" "1" }}
+
+      {{/* If `tags_include` is set, exclude posts with no tags. */}}
+      {{ if and ($page.Params.tags_include) (lt (len .Params.tags) 1) }}
+        {{ $.Scratch.Set "show_post" "0" }}
+      {{end}}
+
+      {{/* If `tags_exclude` is set, exclude posts. */}}
+      {{ range $key, $val := .Params.tags }}
+        {{ if in $page.Params.tags_exclude $val }}
+          {{ $.Scratch.Set "show_post" "0" }}
+        {{end}}
+      {{end}}
+
+      {{ $show_post := $.Scratch.Get "show_post" }}
+      {{ if ne $show_post "0" }}
         {{ $params := dict "post" . "page" $page }}
         {{ partial "post_li" $params }}
-      {{ end }}
+      {{end}}
+
     {{ end }}
 
   </div>