gohugoio / hugo

The world’s fastest framework for building websites.
https://gohugo.io
Apache License 2.0
76.2k stars 7.55k forks source link

Add .HasCodeBlock #10798

Open writeonlycode opened 1 year ago

writeonlycode commented 1 year ago

Hugo already has a .HasShortCode that returns true if a given shortcode was used in the page. I't useful when, for example, we want to include some CSS or JS in the head to handle the content of the shortcode. It would be nice to have a .HasCodeBlock as well, for when we need to include some CSS or JS in the head to handle the content of particular code-blocks.

For example, mermaid diagrams are typically implemented with code blocks like this:

```mermaid
graph TD;
    A-->B;
    A-->C;
    B-->D;
    C-->D;
\```

It would be nice to be able to add something like this in the head:

{{ if .HasCodeBlock "mermaid" }}
...
{{ end }}

It's already possible to do something similar by setting a variable in the codeblock hook, and then adding the JS in the footer or something. But there is currently no way to add it in the head, before the {{ .Content }} is called. I think it would be nice to have this option, as it's typically recommended by the packages to add things in the head of the page. And it's nice to keep all the resources in the same place in the head of the page. (Without using some variable in the front matter like hasMermaid = true...)

bep commented 1 year ago

I agree, but it needs to wait a little, and I'll spend a few lines to explain why:

jmooring commented 1 year ago

But there is currently no way to add it in the head, before the {{ .Content }} is called.

You can force content to be rendered anywhere with something like:

<head>
  ...
  {{ $noop := .WordCount }}
  {{ if .Store.Get "hasMermaid" }}
    ...
  {{ end  }}
  ...
</head>

Any of these will force content rendering:

Content
FuzzyWordCount
Len
Plain
PlainWords
ReadingTime
Summary (regardless of how you define it)
Truncated
WordCount
writeonlycode commented 1 year ago

Oh, that's a nice workaround. Thanks!

king-11 commented 1 month ago

okay I think is the reason why I was seeing https://github.com/gohugoio/hugoDocs/issues/2751#issue-2624562322 and its quite flaky as well because sometimes the store gets populated sometimes it doesnt.

I will update my head to use {{ $noop := .WordCount }} thanks @jmooring