How to check if .Content is empty

Hello,

I want to check if the .md file has content so i can show some special html structure around it. And i cannot find a way (i tried with isset).

{{ if .Content }}
<div class="special-wrapper">
 {{ .Content }}
</div>
{{ end }}

How about len?

3 Likes

@alexandros you are a genius, thank you!

I tend to use with for just about everything. For example:

{{ with .Content }}
  {{- . -}}
{{ end }}
8 Likes

Although, there is a catch!
If there is a comment on the page but no content, with and len methods will not work.

Solution using .RenderString:

{{ if .RenderString .Content }}
  <p>{{- .Content -}}</p>
{{ end }}

I don’t think that’s what you want to do…

content/p1.md

---
title: p1
---
<!-- comment -->

layouts/_default/single.html

{{ .Content | .RenderString }} → "<!-- raw HTML omitted -->\n"

and with this site configuration:


[markup.goldmark.renderer]
unsafe = true

layouts/_default/single.html

{{ .Content | .RenderString }} → "<!-- comment -->\n"

In both cases the result is non-empty, so it doesn’t resolve the edge case you mention.

I tested it on a fresh new site, and you are right, it’s not working as I expected it to. In the project where I got the previous result, the .RenderString method worked! Something unexpected is happening with that project.

I will follow up, and if there is any interesting point, I will mention it. :pray:t2: